一直纠结传统的springbmvc有web.xml配置加载spring的xml文件加载上下文和容器,springboot中添加这些配置,springboot中的@Configuration注解以前也一直用,今天看了下,原来就是加载上下文以及自定义bean到到容器,那么为什么容器不用注解@Component或者@Service注解加载到容器呢,原因@Configuration不仅是加载bean并且是启动执行,里面设置自己需要初始化的方法,在@Configuration注解的类里面的方法上配置@Bean注解下面的方法会在启动时执行,如缓存加载,自定义定时器等,并且可以用@ConditionalOnMissingBean注解给bean启动时设置读取配置参数传参,也可以用@ConfigurationProperties(prefix = "http.connection.pool")传参
implements ApplicationRunner 实现ApplicationRunner接口覆写run方法达到启动加载效果注意需要扫描注解如:@Component,用@Configuration注解实现启动加载bean类似xml配置bean
@Component
public class J2cacheRunner implements ApplicationRunner
{
@Autowired
private ApplicationContext applicationContext;
@Autowired
private OfficialAccountsMapper officialAccountsMapper;
@Autowired
private RestTemplate restTemplate;
@Override
public void run(ApplicationArguments args) throws Exception
{
//启动刷新access_token
RefreshAccessToken.refreshToken();
// 启动加载缓存
Map<String, CacheService> res = applicationContext.getBeansOfType(CacheService.class);
for (CacheService value : res.values())
{
value.load();
}
}
}
implements BeanPostProcessor 实现BeanPostProcessor接口可以拿到ioc容器中所有bean做自己需要的处理如单独分装指定接口的实现类到map中
@Component
public class Dispatcher implements BeanPostProcessor
{
private static Map<Company, Call> calls = new HashMap<Company, Call>();
public static Call getCall(Company category)
{
return calls.get(category);
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException
{
if (bean instanceof LogisticsCall)
{
Call call = (Call) bean;
calls.put(((Call) bean).category(), call);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException
{
return bean;
}
}