@Component与@Configuration区别

时间:2025-02-17 20:56:43

@Component与@Configuration区别


@Configuration本质上还是@Component。

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

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

@Configuration
public class AppConfig {

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

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

    @Value("${}")
    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 = ().setMasterName(master);

        Set<String> redisSet = (redisAddress);
        for (String address : redisSet) {
            (address);
            ((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 {
        ("启动日报定时任务:"+new Date());
        ();
    }


}

【重要区别】

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

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

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