Spring中,修改注入的bean名稱

案例:java

1)、源碼spring

UserService.javaexpress

public interface UserService {}

UserServiceImpl.java ide

@Service
@Transactional
public class UserServiceImpl implements UserService {}

 2)、上下文獲取beancode

系統注入bean時的默認名稱是類名,首字符變成小寫。component

UserService userService = (UserService)xxx.getBean("userServiceImpl");

若是想修改bean名稱,可經過以下方式:xml

1)、繼承AnnotationBeanNameGenerator,重寫generateBeanName生成器繼承

public class CustomAnnotationBeanNameGenerator extends AnnotationBeanNameGenerator {

	/** 
	 * (non-Javadoc)
	 * @see org.springframework.context.annotation.AnnotationBeanNameGenerator#generateBeanName(org.springframework.beans.factory.config.BeanDefinition, org.springframework.beans.factory.support.BeanDefinitionRegistry)
	 */
	@Override
	public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
		String beanName = super.generateBeanName(definition, registry);
		return beanName.endsWith("Impl") ? beanName.substring(0, beanName.length() - 4) : beanName;
	}

}

2)、增長sping.xml配置get

<context:component-scan base-package="XXX.YYY.***.**" use-default-filters="false"
		name-generator="XXX.YYY.ZZ.CustomAnnotationBeanNameGenerator">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

3)、上下文獲取Beangenerator

UserService userService = (UserService)xxx.getBean("userService");
相關文章
相關標籤/搜索