迄今为止,所接触到的Bean都是“无知觉”的,就像黑客帝国中机械工厂里面“养殖”的人类,他们虽然能完成一定的功能,但是根本不知道自己在工厂(BeanFactory)中的代号(id),或者自己是在哪个工厂(BeanFactory的引用)中沉睡。所以,本节的目的就是要创造出一个尼奥一样的Bean,让他知道自己在工厂中的id和自己原来躺在哪个工厂中。这里,称之为,Bean对Spring有知觉。
但是有言在先,如果要在Spring容器中做到这两点,当然,可以自己通过某些方法实现,代价是大量冗余代码,好处是跟Spring解耦。如果使用Spring提供的接口,好处当然减少代码的规模,“缺点”(如果算的话)是与 Spring耦合。总之,无论采取那种办法还是要看实际需要。
beanNameAware接口:
package com.pb.entity;
import org.springframework.beans.factory.BeanNameAware;
/*
* 实体类实现init方法和BeanNameAware接口
*/
public class Hello implements BeanNameAware{
@Override
public void setBeanName(String arg0) {
System.out.println("回调setBeanName方法 id属性是"+arg0);
}
public void init(){
System.out.println("正在执行初始化方法init");
}
}
applicationContext.xml:
<bean id="hello" class="com.pb.entity.Hello" init-method="init"></bean>
package com.pb.demo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.pb.entity.Hello;
public class HelloTest {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
Hello hello=context.getBean("hello",Hello.class);
}
}
结果:
回调setBeanName方法 id属性是hello
正在执行初始化方法init
BeanFactoryAware接口:
package com.pb.entity;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
/*
* 实体类实现init方法和BeanNameAware接口
*/
public class Hello implements BeanNameAware,BeanFactoryAware{
private BeanFactory bf;
@Override
public void setBeanName(String arg0) {
System.out.println("回调setBeanName方法 id属性是"+arg0);
}
public void init(){
System.out.println("正在执行初始化方法init");
}
/*
* 重写setBeanFactory方法
* @see org.springframework.beans.factory.BeanFactoryAware#setBeanFactory(org.springframework.beans.factory.BeanFactory)
*/
@Override
public void setBeanFactory(BeanFactory arg0) throws BeansException {
this.bf=arg0;
}
public BeanFactory getBf() {
return bf;
}
}
package com.pb.demo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.pb.entity.Hello;
public class HelloTest {
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
Hello hello=context.getBean("hello",Hello.class);
System.out.println("得到beanFactory对象 "+hello.getBf());
}
}
结果:
回调setBeanName方法 id属性是hello
正在执行初始化方法init
得到beanFactory对象 org.springframework.beans.factory.support.DefaultListableBeanFactory@3dc0bb: defining beans [hello]; root of factory hierarchy