spring注解@Bean的使用以及@configration和@component区别

注解@Bean的作用是向容器中注入bean,相当于之前配置文件中的bean标签,基本使用如下:

@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {
    private int id;
    private String name;
    private int age;

}

编写一个类,使用@Configuration标注为配置类,作用相当于之前的配置文件,在配置类的方法上使用@Bean注解标注,相当于给容器注册一个bean,类型为返回值的类型,id默认使用方法名作为id,也可以在注解中使用value属性自定义bean的id。

//配置类==配置文件
@Configuration
public class UserConfig {

    //给容器注册一个bean;类型为返回值的类型;id默认使用方法名作为id
    @Bean(value = "user01")
    public User user(){
        return new User(2,"子羽",18);
    }
}
public class MainTest {
    public static void main(String[] args) {
        ApplicationContext annotationConfigApplicationContext =
                new AnnotationConfigApplicationContext(UserConfig.class);
        User user = annotationConfigApplicationContext.getBean(User.class);
        System.out.println(user);
    }
}

测试结果如下

User(id=2, name=子羽, age=18)

下面讨论@configration和@component两个注解的区别,@configration和@component都可以标注在类上作为一个配置类,使用@Configuration注解的类中所有带有@Bean注解的方法都会被CGLib动态代理,因此每次调用方法返回的都是同一个实例,而使用@component注解的类则为一个普通配置类,每次调用方法返回一个新的实例,下面我们来验证一下吧。

1.@configration

@Configuration
public class UserConfig {

    //给容器注册一个bean;类型为返回值的类型;id默认使用方法名作为id
    @Bean(value = "user01")
    public User user(){
        return new User(2,"子羽",18);
    }
}
public class MainTest {
    public static void main(String[] args) {
        ApplicationContext annotationConfigApplicationContext =
                new AnnotationConfigApplicationContext(UserConfig.class);

        UserConfig userConfig = annotationConfigApplicationContext.getBean(UserConfig.class);
        User user1 = userConfig.user();
        User user2 = userConfig.user();
        System.out.println(user1 == user2);
    }
}

测试结果为true

true

另外注意@configration标注配置类不能是final的,final的无法动态代理。

2.@component

@Component
public class UserConfig {

    //给容器注册一个bean;类型为返回值的类型;id默认使用方法名作为id
    @Bean(value = "user01")
    public User user(){
        return new User(2,"子羽",18);
    }
}
public class MainTest {
    public static void main(String[] args) {
        ApplicationContext annotationConfigApplicationContext =
                new AnnotationConfigApplicationContext(UserConfig.class);

        UserConfig userConfig =   
                annotationConfigApplicationContext.getBean(UserConfig.class);            
        User user1 = userConfig.user();
        User user2 = userConfig.user();
        System.out.println(user1 == user2);
    }
}

测试结果为false

false

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值