_____________初学Springboot2

三种依赖注入的方式

1、注解

@Component

public class User {

@Autowired

private ApplicationContext applicationContext;

public void show() {

System.out.println("user:"+applicationContext.getClass());

}

}

2、实现ApplicationContextAware接口

@Component

public class Book implements ApplicationContextAware {

private ApplicationContext applicationcontext;

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

this.applicationcontext=applicationContext;

}

public void show() {

System.out.println("book:"+applicationcontext.getClass());

}

}

3、构造方法直接构造(局限性 1⃣️构造函数只能有一个,如果有多个必须要有无参构造此时spring 就会调用无参,不会调用 applicationcontext

              2⃣️构造函数的参数,必须要在Spring 容器中有 )

@Component

public class Bank {

 private ApplicationContext applicationContext;

public Bank(ApplicationContext applicationContext) {

this.applicationContext=applicationContext;

}

public void show() {

System.out.println("Bank:"+applicationContext.getClass());

}

}

___________________________BeanPostProcesser___________________________

在bean依赖装配(设置完成后)完成触发

这里可以指定Bean做一些处理,比如返回该对象的代理对象

@Component

public class EchoBeanPostProcesser implements BeanPostProcessor {

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {

System.out.println("≈≈≈≈≈≈≈≈≈>>>属性设置之后,init之前"+bean.getClass());

if(bean instanceof User)

return new LogUser();

return bean;

} 

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

System.out.println("≈≈≈≈≈≈≈≈≈>>>属性设置之后,init之后"+bean.getClass());

return bean;

}

}

猜你喜欢

转载自www.cnblogs.com/qiqisx/p/9335723.html