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();
}
}