Bean的生命周期之初始化前、初始化后以及模拟Aop

初始化前

Config

@ComponentScan("com.luban")
public class config {
 @Bean
    public User user(){
     return new User();
 }
}

user

public class User {

}

userService

@Component
public class UserService implements InitializingBean {

    private  User user;


    public UserService() {
        System.out.println("构造方法");
    }
        @Autowired
    public void setUser(User user) {
        System.out.println("set方法注入");
        this.user = user;

    }
    @PostConstruct
    public void xxx(){
        System.out.println("xxx");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(this);
        System.out.println("初始化");
    }
}
LubanBeanPostProcessor
@Component
public class LubanBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")){
            System.out.println("初始化前");
        }

        return null;
    }
}

main

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(config.class);
        UserService userService = applicationContext.getBean("userService", UserService.class);

    }
}

测试

发现xxx方法没有执行,

修改代码 

@Component
public class LubanBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")){
            System.out.println("初始化前");
        }

        return bean;
    }
}

再次测试!!

为什么会出现两种不同情况:

原因是:我们自定义了一个初始化前方法,返回的是null,    而这个注解@PostConstruct底层拿到的是我们返回的null,因此不输出,修改为bean后,此注解就能通过反射执行xxx方法!!! 

 我们再修改一下下:

@Component
public class LubanBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")){
            System.out.println("初始化前");
        }
        for (Method method: bean.getClass().getMethods()){
            if (method.isAnnotationPresent(PostConstruct.class)){
                try {
                    method.invoke(bean);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }

        return bean;
    }
}

再次输出:

发现有两个xxx,PostConstruct底层就是用这种反射机制实现的!!! 

初始化后

在LubanBeanPostProcessor新增初始化方法

     //初始化后方法
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")){
            System.out.println("初始化后");
        }
        return null;
    }

输出:

 那如果返回People对象呢;

修改:

    //初始化后方法
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")){
            System.out.println("初始化后");
            Person person = new Person();
            return person;
        }
        return null;
    }

输出:

最后拿到的Bean就是返回的Person了!!! 

模拟Aop

新增加接口:


public interface UserInterface {
    public void test();
}

 继承接口

@Component
public class UserService  implements InitializingBean,UserInterface {

    private  User user;


    public UserService() {
        System.out.println("构造方法");
    }
        @Autowired
    public void setUser(User user) {
        System.out.println("set方法注入");
        this.user = user;

    }
    @PostConstruct
    public void xxx(){
        System.out.println("xxx");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(this);
        System.out.println("初始化");
    }

    @Override
    public void test() {
        System.out.println("业务逻辑");
    }
}

修改方法

        //初始化后方法
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")){
            Object o = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("代理逻辑");
                    return null;
                }
            });
            return o;

        }
        return null;
    }
}

 输出:

修改下主类

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(config.class);
        UserInterface userService = (UserInterface)( applicationContext.getBean("userService"));
        userService.test();
    }
}

 输出:

 修改

        //初始化后方法
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")){
            Object o = Proxy.newProxyInstance(bean.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    System.out.println("代理逻辑");
                    method.invoke(bean,args);
              return null;
                }
            });
            return o;

        }
        return null;
    }
}

输出:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值