1.获取bean
1.工具类
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(SpringUtil.applicationContext == null){
SpringUtil.applicationContext = applicationContext;
}
}
/**
* 获取ApplicationContext
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
}
2.调用
User user = SpringUtil.getApplicationContext().getBean(User.class);
2.自定义bean
@Component
public class BeanConfig {
@Bean
public User user(){
return new User();
}
}
参考:
springboot-training/springboot-bean at master · gsonkeno/springboot-training · GitHub