@Configuration是为了完全的取消xml配置文件而改用注解。下面将对其进行对比说明:
@Configuration与@Bean
一般来说@Configuration与@Bean注解搭配使用。
@Configuration等价于xml配置中的<beans></beans>;
@Bean等价于xml配置中的<bean></bean>
下面为xml配置:
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-lazy-init="true" default-autowire="default">
<bean id="student" class="com.demo.enity.Student"
init-method="init" destroy-method="destroy" lazy-init="false">
<property name="age" value="18"/>
<property name="name" value="test"/>
</bean>
</beans>
等价于:
@Configuration
@Lazy(true)
public class BeanConfiguration {
@Bean(name = "student", initMethod = "init", destroyMethod = "destroy")
@Scope("prototype")
public Student getStudent(){
Student student = new Student();
student.setAge(18);
student.setName("test");
return student;
}
定义了bean之后什么时候加载呢,这个时候就说到@Lazy这个注解了,@Lazy注解用于标识bean是否需要延迟加载
在上面的getStudent中打上断点时你会发现:
当没有@Lazy注解或为false时,启动就会进入getStudent()方法,实例化并返回这个Student对象。
当@Lazy注解为true时,只有在其他地方注入Student对象时,启动才会进入getStudent()方法,实例化Student对象。
总结:@Configuration与@Bean搭配使用,作用就是定义bean,并返回bean对象实例;
后面在其他类中注入的bean实例就是@Configuration与@Bean定义的bean对象实例。
刚刚学习注解,如有错误麻烦各位大神帮忙指正。