@Component与@Configuration区别

@Component与@Configuration区别


@Configuration本质上还是@Component。

@Configuration标记的类必须符合下面的要求:
1.配置类不能是 final 类
2.配置注解通常为了通过 @Bean 注解生成 Spring 容器管理的类,
3.配置类必须是非本地的(即不能在方法中声明,不能是 private)。

Spring 容器在启动时,会加载默认的一些PostPRocessor,其中就有ConfigurationClassPostProcessor,
这个后置处理程序专门处理带有@Configuration注解的类,这个程序会在bean 定义加载完成后,在bean初始化前进行处理

@Configuration
public class AppConfig {

    //	集群
    @Value("${redis.sentinel}")
    private String redisAddress;

    @Value("${redis.master}")
    private String master;

    @Value("${redis.password}")
    private String password;

    @Autowired
    private UserFeignClient userFeignClient;

    @Bean
    public ThreadPool threadPool() {
        return new ThreadPool(100);
    }

    @Bean
    public BeanChangeUtil beanChangeUtil() {
        return new BeanChangeUtil(userFeignClient);
    }

    @Bean("redissonConfig")
    public Config getRedisConfig() {
        Config config = new Config();

        SentinelServersConfig ssc = config.useSentinelServers().setMasterName(master);

        Set<String> redisSet = StringUtils.commaDelimitedListToSet(redisAddress);
        for (String address : redisSet) {
            ssc.addSentinelAddress(address);
            ssc.setPassword(AESUtil.AESDecrypt(password,"ECB"));
        }

        return config;
    }
}
@Component
@Order(value = 1)
public class StartService implements ApplicationRunner {

    @Autowired
    private PointToPointTask pointToPointTask;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("启动日报定时任务:"+new Date());
        pointToPointTask.start();
    }


}

【重要区别】

@Component:会当做配置类,但不会为其生成CGLIB代理class

@Configuration:会当做配置类,但会为其生成CGLIB代理class

在获取当前类名时,使用@Component获取的是当前类名;而@Configuration获取的是当前类名+唯一标识(CGLIB代理)

  • 20
    点赞
  • 56
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值