我尝试定义一个包含@Configuration和@ImportResource的客户注释
但@ImportResource不起作用
有什么建议吗?
@Documented
@Configuration
@ImportResource
@Target({ElementType.TYPE})
@Order(Ordered.HIGHEST_PRECEDENCE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableXXConfiguration {
@AliasFor(annotation = ImportResource.class , attribute = "value")
String[] value() default {};
}
答案 0 :(得分:0)
@ImportResource包含两个属性值和位置。 value属性最终是locations属性的别名,因此使用任何一个别名都可以正常工作。保持您的自定义注释(EnableXXConfiguration)声明(使用值属性的声明),使用下面的代码片段。
@EnableXXConfiguration(value = { "context1.xml", "com/example/stackoverflow/context2.xml"})
public class DemoApp {
@Autowired
private BeanA beanA;
@Autowired
private BeanB beanB;
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoApp.class);
DemoApp demoAppObj = (DemoApp) context.getBean("demoApp");
System.out.println("BeanA member: " + demoAppObj.getBeanA());
System.out.println("BeanB member: " + demoAppObj.getBeanB());
}
public BeanA getBeanA() {
return beanA;
}
public BeanB getBeanB() {
return beanB;
}
}
假设我们在两个不同的位置使用两个xmlss。 context1.xml放在资源文件夹(src / main / resource)中,context2.xml放在任何其他位置(此处为:src / main / java / com / example / stackoverflow)
context1.xml
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="beanA" class="com.example.stackoverflow.BeanA" />
</beans>
context2.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<bean id="beanB" class="com.example.stackoverflow.BeanB" />
</beans>