业务开发(五)—— Java代码

时间:2023-12-24 23:30:37

Bean生命周期


@Component
public class BeanTest implements BeanFactoryAware, BeanNameAware,
InitializingBean, DisposableBean { private String name;
private String address;
private int phone; private BeanFactory beanFactory;
private String beanName; public BeanTest() {
System.out.println("【构造器】调用Person的构造器实例化");
} public String getName() {
return name;
} public void setName(String name) {
System.out.println("【注入属性】注入属性name");
this.name = name;
} public String getAddress() {
return address;
} public void setAddress(String address) {
System.out.println("【注入属性】注入属性address");
this.address = address;
} public int getPhone() {
return phone;
} public void setPhone(int phone) {
System.out.println("【注入属性】注入属性phone");
this.phone = phone;
} @Override
public String toString() {
return "Person [address=" + address + ", name=" + name + ", phone="
+ phone + "]";
} // 这是BeanFactoryAware接口方法
@Override
public void setBeanFactory(BeanFactory arg0) throws BeansException {
System.out
.println("【BeanFactoryAware接口】调用BeanFactoryAware.setBeanFactory()");
this.beanFactory = arg0;
} // 这是BeanNameAware接口方法
@Override
public void setBeanName(String arg0) {
System.out.println("【BeanNameAware接口】调用BeanNameAware.setBeanName()"+arg0);
this.beanName = arg0;
} // 这是InitializingBean接口方法
@Override
public void afterPropertiesSet() throws Exception {
System.out
.println("【InitializingBean接口】调用InitializingBean.afterPropertiesSet()");
} // 这是DiposibleBean接口方法
@Override
public void destroy() throws Exception {
System.out.println("【DiposibleBean接口】调用DiposibleBean.destory()");
} // 通过<bean>的init-method属性指定的初始化方法
public void myInit() {
System.out.println("【init-method】调用<bean>的init-method属性指定的初始化方法");
} // 通过<bean>的destroy-method属性指定的初始化方法
public void myDestory() {
System.out.println("【destroy-method】调用<bean>的destroy-method属性指定的初始化方法");
} }

BeanPostProcessor.postProcessBeforeInitialization,应用BeanPostProcessor在所有Bean初始化之前进行调用方法。

BeanPostProcessor.postProcessAfterInitialization,应用BeanPostProcessor在所有Bean初始化之后进行调用方法。


@Component
public class BeanPostProcessorTest implements BeanPostProcessor { public BeanPostProcessorTest() {
super();
System.out.println("这是BeanPostProcessor实现类构造器!!");
} @Override
public Object postProcessAfterInitialization(Object arg0, String arg1)
throws BeansException {
if (arg0 instanceof BeanTest) {
System.out
.println("BeanPostProcessor接口方法postProcessAfterInitialization对属性进行更改!");
}
return arg0;
} @Override
public Object postProcessBeforeInitialization(Object arg0, String arg1)
throws BeansException {
if (arg0 instanceof BeanTest) {
System.out
.println("BeanPostProcessor接口方法postProcessBeforeInitialization对属性进行更改!");
}
return arg0;
} }

Autowired注解

  1. 默认按照类型去容器中找
  2. 若存在多个类型,则通过属性名作为ID去容器中找