java学习

java学习

 

利用BeanPostProcessor接口实现bean初始化的前后执行方法

1、aop的简单实现
public class User implements InitializingBean,DisposableBean{
public String toString() {
System.out.println("userdddd");
return "444";
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println(" user afterPropertiesSet");
}
@Override
public void destroy() throws Exception {
System.out.println("user destroy");
}
}
public class LogUser extends User{
public String toString() {
System.out.println("log start");
super.toString();
System.out.println("log end");
return "";
}
}
public interface MyApplicationContextAware {
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
}
@Component
public class Dog4 implements MyApplicationContextAware{
ApplicationContext applicationContext;
public ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext=applicationContext;
}
}
@Component
public class MyBeanPostProcessor implements BeanPostProcessor{
@Autowired
ApplicationContext applicationContext;
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessAfterInitialization=="+beanName);
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("postProcessBeforeInitialization=="+beanName);
if(bean instanceof User) {
return new LogUser();
}
if(bean instanceof MyApplicationContextAware) {
MyApplicationContextAware my=(MyApplicationContextAware) bean;
my.setApplicationContext(applicationContext);
}
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
}
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext aa=new AnnotationConfigApplicationContext("com.yjw");
Dog4 dog = aa.getBean(Dog4.class);
System.out.println(dog.getApplicationContext());
User user = aa.getBean(User.class);
System.out.println(user.toString());
aa.close();
}
}

posted on 2018-03-06 15:34 杨军威 阅读(467) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜