@Configuration 用法说明
@Configuration 注解的作用域为类,专门用于配置构造、初始化、组件组装。
主要有三种使用场景:
1、 初始化配置模型
@Inject("${liteflow}") //@Inject 作用在类上,只与 @Configuration 配合才有效
@Configuration
public class LiteflowProperty {
private boolean enable;
private String ruleSource;
private String ruleSourceExtData;
...
}
2、 构建或组装对象进入容器
@Configuration
public class DemoConfig {
@Bean(value = "db1", typed = true)
public DataSource db1(@Inject("${demo.db1}") HikariDataSource ds){
return ds;
}
@Bean
public void db1_cfg(@Db("db1") MybatisConfiguration cfg) {
MybatisPlusInterceptor plusInterceptor = new MybatisPlusInterceptor();
plusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
cfg.setCacheEnabled(false);
cfg.addInterceptor(plusInterceptor);
}
//也可以带条件处理
@Bean
public CacheService cache(@Inject("${cache.enable}") boolean enable,
@Inject("${cache.config}") CacheServiceSupplier supper){
if(enable){
return supper.get();
}else{
return null;
}
}
}
3、 初始化一些设置,或者导入一些配置
@PropertySource("classpath:demo-2.yml")
@Configuration
public class Config {
@Bean
public AuthAdapter adapter() {
return new AuthAdapter()
.loginUrl("/login") //设定登录地址,未登录时自动跳转
.addRule(r -> r.include("**").verifyIp().failure((c, t) -> c.output("你的IP不在白名单"))) //添加规则
.addRule(b -> b.exclude("/login**").exclude("/_run/**").verifyPath()) //添加规则
.processor(new AuthProcessorImpl()) //设定认证处理器
.failure((ctx, rst) -> {
ctx.render(rst); //设定默认的验证失败处理;也可以用过滤器捕促异常
});
}
}