<?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>
複製代碼
啓動類以下spring
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);
}
複製代碼
獲得以下輸出bash
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配置app
<bean id="factoryMethod" class="smaug.customer.service.controller.designMode.bean.FactoryMethodTest" factory-method="getBean"/>
複製代碼
啓動類ide
System.out.println("factorymethod => " +applicationContext.getBean("factoryMethod"));
複製代碼
結果post
factorymethod => smaug.customer.service.controller.designMode.bean.HelloWorld@621624b1
複製代碼
bean 的後置處理器,bean實例化後,咱們能夠經過實現 BeanPostProcessor來對bean 作一些後置處理,大名鼎鼎的AOP 就是經過後置織入的方式實現的ui
BeanPostProcessor源碼以下spa
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
複製代碼