import annotation based spring project in xml based project

Viewed 283

I have two spring projects,

Project A: is built using xml bean confguration.

Project B : is built using Annotations; and A depends on B;

how can I load B beans inside the A applicationContext.

I searched but I found how to load xml beans using annotations : @ImportResource

Is there a way to do so without having to create two application context :

ApplicationContext applicationContextA = new ClassPathXmlApplicationContext("classpath:/applicationContextA.xml");

ApplicationContext applicationContextB = new AnnotationConfigApplicationContext(BConfiguration.class);
1 Answers

Yes, You Can Use One Application Context

You can use a combination of both xml and annotation based configuration using either ApplicationContext implementation. So you can choose one and implement it using one of the following methods.

With ClassPathXmlApplicationContext

When using xml you want to activate package scanning in your xml file.

In the xml:

<context:component-scan base-package="com.yourdomain.packetstoscan"/>
<bean id="myXmlConfiguredBean" class="com.yourdomain.MyXmlConfiguredBean"/>

With AnnotationConfigApplicationContext

When using annotations you want to include the xml file with an annotation on your config class.

In your Java configuration class:

@Configuration
@ImportResource("classpath:yourContext.xml")
public class MyAnnotationConfiguredBean { }

Bean Creation Order

When testing this I noticed just one minor difference, which was the bean creation order. However, I do not think this should have any influence on your application. I'm just adding this for the sake of completeness.

For Xml based config:

INFO com.yourdomain.MyXmlApp - BEAN: myAnnotationConfiguredBean
INFO com.yourdomain.MyXmlApp - BEAN: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
INFO com.yourdomain.MyXmlApp - BEAN: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
INFO com.yourdomain.MyXmlApp - BEAN: org.springframework.context.event.internalEventListenerProcessor
INFO com.yourdomain.MyXmlApp - BEAN: org.springframework.context.event.internalEventListenerFactory
INFO com.yourdomain.MyXmlApp - BEAN: myXmlConfiguredBean

For Annotation based:

INFO com.yourdomain.MyApp - BEAN: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
INFO com.yourdomain.MyApp - BEAN: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
INFO com.yourdomain.MyApp - BEAN: org.springframework.context.event.internalEventListenerProcessor
INFO com.yourdomain.MyApp - BEAN: org.springframework.context.event.internalEventListenerFactory
INFO com.yourdomain.MyApp - BEAN: myAnnotationConfiguredBean
INFO com.yourdomain.MyApp - BEAN: myXmlConfiguredBean
Related