欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring :使用ApplicationContextAware接口

程序员文章站 2022-05-25 16:21:33
...
/**
*使用ApplicationContextAware接口
*/
package exm.spring.bean;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class Service implements ApplicationContextAware {
	
	private ApplicationContext applicationContext;

	public ApplicationContext getApplicationContext() {
		return applicationContext;
	}
	
	public User createUser()
	{
		User user = applicationContext.getBean("user", User.class);
			
		return user;
	}

	/**
	 * 实现该方法为了在该bean内获得容器
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		
		this.applicationContext = applicationContext;
		
	}

}

/**
*使用抽象类
*/
package exm.spring.bean;

public abstract class AbstractService {
	
	//抽象bean无法配置。如果要配置需要配置<lokup-method>子标签,spring容器将自动实现该abstract方法
	public abstract User createUser();

}

<!-- 配置文件 -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:p="http://www.springframework.org/schema/p"
    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">
        
        
        <!-- 下面配置相当于:
        
        		让spring创建AbstractService的子类,并实现createUser方法,
        		让外部请求得到userFromAbstractService
        
         -->
        <bean id="userFromAbstractService" class="exm.spring.bean.User" scope="prototype"/>
        
        <bean id="abstractService" class="exm.spring.bean.AbstractService" >
        	<lookup-method name="createUser" bean="userFromAbstractService"/>
        </bean>
        
</beans>


转载于:https://my.oschina.net/ChiLin/blog/387089