在基于XML配置的中,根元素是来自与Spring Bean命名空间的<beans>元素。在基于Java的配置中使用@Configuration注解的Java类,就等价于XML配置中的<beans>元素。
在基于Java的配置中使用AnnotationConfigApplicationContext来创建Spring上下文。
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
@Configuration
@Configuration注解会作为一个标识告知Spring:这个类将包含一个或者多个Spring Bean的定义。这些Bean的定义是使@Bean注解所标注的方法。
@Configuration
public class SpringConfig {
@Bean()
public Student student(){
return new Student();
}
@Bean
public StudentService studentService(){
return new StudentService();
}
}
@Bean
使用 @Bean 注解,注解到方法之上,使其成为 Spring 中返回对象为 Spring 的 Bean 资源。他等价于我们之前使用XML所配置的<bean>元素。
@Bean 的配置项中包含 4 个配置项:
-
name
: 是一个字符串数组,允许配置多个 BeanName -
autowire
: 标志是否是一个引用的 Bean 对象,默认值是 Autowire.NO -
initMethod
: 自定义初始化方法 -
destroyMethod
: 自定义销毁方法
如果没有显示指定name,Spring将默认使用方法名作为bean name。
@Bean()
public Student student(){
return new Student();
}
注入属性值
使用xml配置的时候,我们可以通过元素<property>和<constructor-arg>来为bean对象注入属性值,而在基于Java的配置中,我们只需要通过构造函数或者setter方法就可以了。
@Bean()
public Student student(){
Student student = new Student("wyw");
student.setAge("24");
return student;
}
@Bean
public StudentService studentService(){
return new StudentService(student());
}
在Spring的Java配置中,通过声明方法引用一个Bean并不等于调用该方法。如果真的是这样,那么每次调用都将得到该Bean的一个新实例。实际上,通过@Bean注解标注的方法会告知Spring我们希望定义的Bean要被注册进Spring的应用上下文中。因此,在其他Bean的声明方法中引用这个方法时,Spring都会拦截该方法的调用,并尝试在应用上下文中查找该Bean,而不是让方法创建一个新的实例。
网友评论