Bean的后置处理器

Bean的后置处理器,第1张

Bean的后置处理器

user:
@Component
public class User {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
 userService
@Component
public class UserService {
 
}
person
public class Peroson {
}
config
@ComponentScan("com.luban")
public class config {

}

 再没有Bean的后置处理器实现类之前

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

        UserService userService = applicationContext.getBean("userService", UserService.class);
        System.out.println(userService);

    }
}

输出;

 Bean的后置处理器
@Component
public class LubanBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return new Peroson();
    }
}

测试输出

意思是userservice实际的类型的people ,但我们强行转成Userservice失败,因此报错,那为什么是people类型呢?

原因在于:

 上面箭头所指,实现了将Uservice类型的bean被替换成people类型的!!!

总结:

 实现类中这两个方法就是用来 *** 作传过来的对象的,参数bean代表传过来的对象,也就是Userservice,beanName代表对象名

修改代码:

 @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals("userService")){
            System.out.println(beanName);
            System.out.println(bean);
        }
        return new Peroson();
    }

 输出:

修改代码:

 @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
     
            System.out.println(beanName);
            System.out.println(bean);
        
        return new Peroson();
    }

 输出:

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5636628.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存