Spring中使用BeanPostProcessor須要注意的地方

Spring中Bean的實例化過程以下:

 

其中BeanPostProcessor的前置和後置處理的方法中都要返回該bean,不能是null,否則在getBean的時候獲取不到。java

public interface PasswordDecodable
{
	public String getEncodedPassword();
	
	public void setDecodedPassword(String password);
}

public class LoginModel implements PasswordDecodable
{

	private String password;
	
	public LoginModel()
	{
		
	}
	
	public LoginModel(String password)
	{
		this.password = password;
	}
	
	@Override
	public String getEncodedPassword()
	{
		// TODO Auto-generated method stub
		return this.password;
	}

	@Override
	public void setDecodedPassword(String password)
	{
		// TODO Auto-generated method stub
		this.password = password;
	}

}

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import com.uqee.spring.beans.PasswordDecodable;
import com.uqee.utils.Md5Token;

public class PasswordDecodePostProcessor implements BeanPostProcessor
{

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException
	{
		// TODO Auto-generated method stub
		return bean;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException
	{
		// TODO Auto-generated method stub
		if(bean instanceof PasswordDecodable)
		{
			String encodedPassword = ((PasswordDecodable)bean).getEncodedPassword();
			String decodePassword = decodePassword(encodedPassword);
			((PasswordDecodable)bean).setDecodedPassword(decodePassword);
		}
		return bean;
	}
	
	private String decodePassword(String encodePassword)
	{
		return Md5Token.getInstance().getLongToken(encodePassword);
	}
}

<bean id="loginModel" class="com.uqee.spring.beans.LoginModel">
	    <constructor-arg index="0">
	        <value>demo</value>
	    </constructor-arg>
</bean>

PasswordDecodePostProcessor的postProcessAfterInitialization和postProcessBeforeInitialization均不能返回null,否則下列代碼:
ConfigurableListableBeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext3.xml"));
		factory.addBeanPostProcessor(new PasswordDecodePostProcessor());
		PasswordDecodable passwordDecodable = (PasswordDecodable)factory.getBean("loginModel");
中passwordDecodable會是null引用。
相關文章
相關標籤/搜索