Spring基础(6) : 普通Bean对象中保存ApplicationContext
public class Person implements ApplicationContextAware{ ApplicationContext context; public String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } public void printP1name(){ Person p= context.getBean("p1",Person.class); System.out.println("p1name="+p.getName()); } }
Person类实现 ApplicationContextAware ,在创建该bean的时候,会将context注入到bean中。
public class Main { public static void main(String[] args){ ApplicationContext context = new ClassPathXmlApplicationContext("a.xml"); Person p = context.getBean("p",Person.class); p.printP1name(); } }
<?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-3.0.xsd"> <bean id="p1" class="com.Person"> <property name="name" value="p1"/> </bean> <bean id="p" class="com.Person"/> </beans>
打印:
p1name=p1