Skip to content
目录概览

Spring 提供了哪些配置方式?

  • 基于xml配置 bean 所需的依赖项和服务在 XML 格式的配置文件中指定 。 这些配置文件通常包含许多 bean 定义和特定于应用程序的配置选项。 它们通常以 bean 标签开头。例如:

    xml
    <bean id="studentbean" class="org.edureka.firstSpring.StudentBean"> 
      <property name="name" value="Edureka"></property>
    </bean>
    
    1
    2
    3
  • 基于注解配置 您可以通过在相关的类,方法或字段声明上使用注解,将 bean 配置为组件类本身,而不是使用 XML 来描述 bean 装配。 默认情况下, Spring 容器中未打开注解装配。 因此,您需要在使用它之前在 Spring 配置文件中启用它。 例如:

    xml
    <beans>
    <context:annotation-config/>
    <!-- bean definitions go here -->
    </beans>
    
    1
    2
    3
    4
  • 基于 Java API 配置 Spring的Java配置是通过使用@Bean和@Configuration来实现 。

    • @Bean
      注解扮演与元素相同的角色 。
    • @Configuration 类 允许通过简单地调用同一个类中的其他@Bean方法来定义bean间依赖关系。

    例如:

    java
    @Configuration
    public class StudentConfig {
      @Bean
      public StudentBean myStudent() {
        return new StudentBean();
      }
    }
    
    1
    2
    3
    4
    5
    6
    7