Spring注解之@Configuration与@Bean

本文主要介绍了@Configuration注解用于取消xml配置文件改用注解,它常与@Bean搭配使用,@Configuration等价于xml中的<beans>,@Bean等价于<bean>。还提到了@Lazy注解用于标识bean是否延迟加载,总结了@Configuration与@Bean的作用是定义并返回bean对象实例。

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

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值