<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="hello" class="smaug.customer.service.bean.Arequest"/>
<alias name="hello" alias="hello2"/>
<alias name="hello2" alias="hello3"/>
</beans>
复制代码
启动类如下
public static void main(String[] args) {
ConfigurableApplicationContext cx = (ConfigurableApplicationContext) SpringApplication.run(CustomerServiceApplication.class, args);
SpringApplication springApplication = new SpringApplication(CustomerServiceApplication.class);
String configLocation = "a.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(configLocation);
System.out.println(" hello2 -> " + applicationContext.getBean("hello2"));
System.out.println("hello3 -> " + applicationContext.getBean("hello3"));
springApplication.run(args);
}
复制代码
得到如下输出
hello -> smaug.customer.service.bean.Arequest@4dd2ef54 hello2 -> smaug.customer.service.bean.Arequest@4dd2ef54 hello3 -> smaug.customer.service.bean.Arequest@4dd2ef54 复制代码
public class BeanTest {
public static void test() {
System.out.println("!23");
}
}
复制代码
public class BeanFactoryBean implements FactoryBean<BeanTest>{
private BeanTest beanTest;
/**
* 获取bean示例
* @return
* @throws Exception
*/
@Override
public BeanTest getObject() throws Exception {
if (Objects.isNull(beanTest)){
return new BeanTest();
}
return beanTest;
}
/**
* 返回class
* @return
*/
@Override
public Class<?> getObjectType() {
return BeanTest.class;
}
/**
* 是否是单例对象
* @return
*/
@Override
public boolean isSingleton() {
return false;
}
复制代码
xml 文件配置如下
beanTest1 => smaug.customer.service.controller.designMode.bean.BeanTest@5203c80f beanTest2 => smaug.customer.service.controller.designMode.bean.BeanFactoryBean@439f2d87 复制代码
public class FactoryMethodTest {
public static HelloWorld getBean() {
return new HelloWorld();
}
}
复制代码
xml配置
<bean id="factoryMethod" class="smaug.customer.service.controller.designMode.bean.FactoryMethodTest" factory-method="getBean"/> 复制代码
启动类
System.out.println("factorymethod => " +applicationContext.getBean("factoryMethod"));
复制代码
结果
factorymethod => smaug.customer.service.controller.designMode.bean.HelloWorld@621624b1 复制代码
bean 的后置处理器,bean实例化后,我们可以通过实现 BeanPostProcessor来对bean 做一些后置处理,大名鼎鼎的AOP 就是通过后置织入的方式实现的
BeanPostProcessor源码如下
public interface BeanPostProcessor {
/**
* bean 初始化前调用的方法
*/
Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
/**
* bean 初始化后调用的方法
*/
Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
复制代码
hello before smaug.customer.service.bean.Arequest@14b8a751 hello after smaug.customer.service.bean.Arequest@14b8a751 复制代码