为Spring对象添加感知属性
Spring中获取的对象,存在许多隐藏属性。如果想要把这些隐藏的属性,添加到对象中,只需要使该类实现对应的感知接口就可以了。
实例
Spring中可以被赋值的感知属性有10多个,下面就为一个对象添加几个感知属性。
感知属性:这个对象的名字,类加载,配置环境等相关的属性。
为UserService 添加3个感知属性
public class UserService implements ApplicationContextAware,BeanFactoryAware,BeanNameAware{
private ApplicationContext ac;
private BeanFactory beanFactory;
private String beanName;
public ApplicationContext getAc() {
return ac;
}
public BeanFactory getBeanFactory() {
return beanFactory;
}
public String getBeanName() {
return beanName;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ac = applicationContext;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
}
测试
@Test
public void test2(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService us = (UserService) ac.getBean("userService");
BeanFactory beanFactory = us.getBeanFactory();
String beanName = us.getBeanName();
ApplicationContext ac2 = us.getAc();
System.out.println("beanFactory:"+beanFactory);
System.out.println("beanName:"+beanName);
System.out.println("ApplicationContext:"+ac2);
}
输出打印
beanFactory:org.springframework.beans.factory.support.DefaultListableBeanFactory@5bcab519: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,userService]; root of factory hierarchy
beanName:userService
ApplicationContext:org.springframework.context.support.ClassPathXmlApplicationContext@4cc77c2e: startup date [Fri Jul 05 19:52:25 CST 2019]; root of context hierarchy
所需jar包
com.springsource.org.apache.commons.logging-1.1.1.jar
spring-aop-4.3.10.RELEASE.jar
spring-aspects-4.3.10.RELEASE.jar
spring-beans-4.3.10.RELEASE.jar
spring-context-4.3.10.RELEASE.jar
spring-core-4.3.10.RELEASE.jar
spring-expression-4.3.10.RELEASE.jar