spring 提供了哪些配置方式?

基于 xml 配置

bean 所需的依赖项和服务在 XML 格式的配置文件中指定。这些配置文件通常

包含许多 bean 定义和特定于应用程序的配置选项。它们通常以 bean 标签开

头。

例如:

<bean id="studentbean" class="org.edureka.firstSpring.StudentBean">

<property name="name" value="Edureka"></property>

</bean>基于注解配置

您可以通过在相关的类,方法或字段声明上使用注解,将 bean 配置为组件类本

身,而不是使用 XML 来描述 bean 装配。默认情况下,Spring 容器中未打开

注解装配。因此,您需要在使用它之前在 Spring 配置文件中启用它。例如:

<beans>

<context:annotation-config/>

<!-- bean definitions go here -->

</beans>

基于 Java API 配置

Spring 的 Java 配置是通过使用 @Bean 和 @Configuration 来实现。

1、 @Bean 注解扮演与 <bean/> 元素相同的角色。

2、 @Configuration 类允许通过简单地调用同一个类中的其他 @Bean 方法

来定义 bean 间依赖关系。

例如:

@Configuration

public class StudentConfig {

@Bean

public StudentBean myStudent() {

return new StudentBean();

}

}

猜你喜欢

转载自www.cnblogs.com/programb/p/13019654.html