Spring注解之@Configuration与@Bean

@Configuration是为了完全的取消xml配置文件而改用注解。下面将对其进行对比说明:

@Configuration与@Bean

一般来说@Configuration与@Bean注解搭配使用。

@Configuration等价于xml配置中的

@Bean等价于xml配置中的

下面为xml配置:




    
        
        
    

等价于:

@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对象实例。

 

刚刚学习注解,如有错误麻烦各位大神帮忙指正。

你可能感兴趣的:(注解,Spring)