为Spring对象添加感知属性

为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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值