Spring 注解@ComponentScan, @Import

2022-12-23  本文已影响0人  Tinyspot

1. @ComponentScan

1.1 @ComponentScans

@ComponentScan("org.example.xxx1")
@ComponentScan("org.example.xxx2")
// 等价
@ComponentScans({
        @ComponentScan("com.example.xxx1"),
        @ComponentScan("com.example.xxx2")
})

2. @Import 导入组件

@Configuration
@Import(CustomConfig.class)
public class UserConfig {
}

配置类

@Configuration
public class CustomConfig {
    @Bean
    public User query() {
        return new User("yuan", 25);
    }
}

2.1 @Import 高级用法

3. @ImportResource 原生配置文件引入

情况一:老项目里是 xml 文件配置
情况二:第三方 jar 里是 xml 文件

@ImportResource("classpath:beans.xml")
public class MyConfig {}

4. @PropertySource 属性值绑定

@Configuration
@PropertySource("classpath:config/config.properties")
public class UserConfig {
    @Bean("user")
    public User updateUser() {
        return new User("Tinyspot", 12);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读