Rectangle 27 7

@Bean
public MarshallingHttpMessageConverter marshallingMessageConverter() {
    return new MarshallingHttpMessageConverter(
        jaxb2Marshaller(),
        jaxb2Marshaller()
    );
}

@Bean
public Jaxb2Marshaller jaxb2Marshaller() {
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setClassesToBeBound(new Class[]{
               twitter.model.Statuses.class
    });
    return marshaller;
}

Convert Spring XML-based to Java-Based Configuration - Stack Overflow

java xml spring configuration spring-annotations
Rectangle 27 2

setClassesToBeBound takes a vararg list, so you can just do this:

Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(User.class);

Convert Spring XML-based to Java-Based Configuration - Stack Overflow

java xml spring configuration spring-annotations
Rectangle 27 7

@Configuration is the heart of the Java-based configuration mechanism that was introduced in Spring 3. It provides an alternative to XML-based configuration.

So the 2 following snippets are identical:

<beans ...>
    <context:component-scan base-package="my.base.package"/>
    ... other configuration ...
</beans>
@Configuration
@ComponentScan(basePackages = "my.base.package")
public class RootConfig {
    ... other configuration ...
}

In both cases Spring will scan in my.base.package and below for classes annotated with @Component or one of the other annotations that are meta-annotated with @Component such as @Service.

difference between @Component and @Configuration in Spring 3 - Stack O...

spring-3
Rectangle 27 10

from my experience, I would prefer(or rather am forced by limitations) to use a combination of XML and annotation based DI . If I need to inject a Map of elements inside a bean , I would have to define a util:map and autowire it . Also, I need to use XML DI to inject datasource into the sessionFactory if I have multiple datasources and so on . So a combination of both would be requited .

I prefer the usage of component-scan to autodetect the services and Dao . This cuts down a lot of Configuration (We cut down the configuration files by around 50% switching to component-scan). Annotation based DI supports both byName(@Resource) and byType(@Autowired).

In short my advice to be to go for a fixture of both . I feel that more annotation support will definitely be on cards in future Spring releases.

java - Spring annotation-based DI vs xml configuration? - Stack Overfl...

java spring configuration dependency-injection annotations
Rectangle 27 6

  • The XML configuration is at one place, instead of being scattered all over the source code in case of annotations. Some people may argue that IDEs like STS allow you to look at all annotations based configuration in one place, but I never like having dependencies on IDEs.
  • Its takes a little more efforts to write XML config, but it saves a lot of time later when you search for dependencies and try to understand the project.
  • XML keeps configuration well organized and simple. Hence is easier to understand, it helps new relatively inexperienced team members get up to speed quickly.
  • Allows you to change the config without a need to recompile and redeploy code. So it is better, when it comes to production support.

So in short XML configuration takes a little more efforts, but it saves you a lot of time & headache later in big projects.

java - Spring annotation-based DI vs xml configuration? - Stack Overfl...

java spring configuration dependency-injection annotations
Rectangle 27 9

from my experience, I would prefer(or rather am forced by limitations) to use a combination of XML and annotation based DI . If I need to inject a Map of elements inside a bean , I would have to define a util:map and autowire it . Also, I need to use XML DI to inject datasource into the sessionFactory if I have multiple datasources and so on . So a combination of both would be requited .

I prefer the usage of component-scan to autodetect the services and Dao . This cuts down a lot of Configuration (We cut down the configuration files by around 50% switching to component-scan). Annotation based DI supports both byName(@Resource) and byType(@Autowired).

In short my advice to be to go for a fixture of both . I feel that more annotation support will definitely be on cards in future Spring releases.

java - Spring annotation-based DI vs xml configuration? - Stack Overfl...

java spring configuration dependency-injection annotations
Rectangle 27 2

  • The XML configuration is at one place, instead of being scattered all over the source code in case of annotations. Some people may argue that IDEs like STS allow you to look at all annotations based configuration in one place, but I never like having dependencies on IDEs.
  • Its takes a little more efforts to write XML config, but it saves a lot of time later when you search for dependencies and try to understand the project.
  • XML keeps configuration well organized and simple. Hence is easier to understand, it helps new relatively inexperienced team members get up to speed quickly.
  • Allows you to change the config without a need to recompile and redeploy code. So it is better, when it comes to production support.

So in short XML configuration takes a little more efforts, but it saves you a lot of time & headache later in big projects.

java - Spring annotation-based DI vs xml configuration? - Stack Overfl...

java spring configuration dependency-injection annotations
Rectangle 27 19

There was a project that provided this: "Spring Security Java Config". It was merged into spring-security-config on December 16th, 2013.

README.MD

The Spring Security Java configuration can now be found in spring-security-config-3.2.0.RELEASE+ as part of the Spring Security distribution.

There currently is no easy way to do Spring Security configuration with Java configuration. You must know what the namespace does behind the scenes making it difficult and error prone. For this reason, I would recommend sticking with the Spring Security namespace configuration.

If you really want to do java configuration you can define all the beans manually. To do this you will need to understand the namespace configuration. The first place to look would be Luke blog post Behind the Spring Security namespace. If you get stuck I would refer to the source code of HttpSecurityBeanDefinitionParser

Last if you would like to be on extremely (unsupported) bleeding edge, you might consider the Spring Security Scala config project. Note that this project is a side project and has not been officially released (nor do I know of any plans to officially release it at this time). You can read details about it on the Spring Security Configuration with Scala blog post. This also details out why there is not Java configuration for Spring Security. You might also find the last portion of Getting Started with Spring Security 3.1 useful as it demos the use of the Spring Security scala configuration.

Thank you. The Behind the Spring Security namespace tutorial is helping me to understand that using code-based Spring Security configuration is not viable. A lot of beans are created by the framework so it is useless to use it.

Code-based Spring Security Configuration - Stack Overflow

spring-security spring-java-config
Rectangle 27 1

Here is the difference between annotation based vs java based configuration, may be it will help you to find the answer.

a) In xml based configuration you can define you bean definition/dependency-injections/auto-wiring inside a xml file.

b)If you want to give only the bean definitions inside your XML file and for rest, you want to use annotations then you have to define "context:annotation-config" in your XML file.

c)If you want to use only annotations for all the things then you have to define "context:component-scan" in your XML file.

2.Java based configuration: If you want to use a java based configuration then you have to use @Configuration annotation over your class which you will use to load the container.Now for the bean definition, you can do with in two.

a)In your configuration class @Bean annotations over the factory methods which you give you your bean objects by using the new keyword.

@Bean 
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }

b) @Component/@Service/@Repository/@Controller/@RestController over the class which you want to act as a bean.

When using Java configuration, the @Component annotations become unnecessary. Is it really advisable to mix Java configuration and component scanning?

spring - Java-based vs annotation-based configuration/autowiring - Sta...

spring
Rectangle 27 1

Here is the difference between annotation based vs java based configuration, may be it will help you to find the answer.

a) In xml based configuration you can define you bean definition/dependency-injections/auto-wiring inside a xml file.

b)If you want to give only the bean definitions inside your XML file and for rest, you want to use annotations then you have to define "context:annotation-config" in your XML file.

c)If you want to use only annotations for all the things then you have to define "context:component-scan" in your XML file.

2.Java based configuration: If you want to use a java based configuration then you have to use @Configuration annotation over your class which you will use to load the container.Now for the bean definition, you can do with in two.

a)In your configuration class @Bean annotations over the factory methods which you give you your bean objects by using the new keyword.

@Bean 
   public HelloWorld helloWorld(){
      return new HelloWorld();
   }

b) @Component/@Service/@Repository/@Controller/@RestController over the class which you want to act as a bean.

spring - Java-based vs annotation-based configuration/autowiring - Sta...

spring
Rectangle 27 17

Multi datasources with mybatis are used in my project right now. This is an Example, add to your application.xml

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
    <property name="url" value="${center.connectionURL}"/>
    <property name="username"  value="${userName}"/>
    <property name="password" value="${password}"/>
</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.xxx.dao.center"/>
    <property name="sqlSessionFactoryBeanName" value="cneterSqlSessionFactory"/>
</bean>

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" name="cneterSqlSessionFactory">
    <property name="dataSource" ref="dataSource"></property>
    <property name="mapperLocations" value="classpath*:mapperConfig/center/*.xml"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--center db end-->
<!--exdb-->
<bean id="dataSourceEx" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
    <property name="url" value="${ex.connectionURL}"/>
    <property name="username"  value="${userName}"/>
    <property name="password" value="${password}"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.xxx.dao.ex"/>
    <property name="sqlSessionFactoryBeanName" value="exSqlSessionFactory"/>
</bean>
<bean id="sqlSessionFactoryEx" class="org.mybatis.spring.SqlSessionFactoryBean" name="exSqlSessionFactory">
    <property name="dataSource" ref="dataSourceEx"></property>
    <property name="mapperLocations" value="classpath*:mapperConfig/ex/*.xml"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<bean id="transactionManagerEx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSourceEx"/>
</bean>

Is there a way to do this using Java Configuration?

I have not tried yet. I only use mybatis with spring by XML config.

Mybatis Spring multiple databases Java configuration - Stack Overflow

java spring mybatis
Rectangle 27 61

Yes, Spring does some magic. Check the Spring Docs:

All @Configuration classes are subclassed at startup-time with CGLIB. In the subclass, the child method checks the container first for any cached (scoped) beans before it calls the parent method and creates a new instance.

This means that your the calls to @Bean methods are proxied via CGLIB and therefore the cached version of the bean is returned (a new one is not created).

The default scope of @Beans is SINGLETON, if you specify a different scope such as PROTOTYPE the call will be passed to the original method.

Is it possible to override beans created this way? For example, I have a Spring defined class that directly calls a bean creation method. What I want is that not the bean created by that method is used, but one I define myself (by annotating it with @Bean and @Primary).

Calling a @Bean annotated method in Spring java configuration - Stack ...

java spring cglib
Rectangle 27 12

Also note that depending on use case you can already parameterize using properties file per environment and PropertySourcesPlaceholderConfigurer

@JmsListener(destinations = "${some.key}")

This is exactly what I was after. Templating is demonstrated for @Value annotations but it wasn't made clear in the docs that it was available more generally. Thanks!

Spring 4.1 @JmsListener configuration - Stack Overflow

spring spring-annotations spring-jms
Rectangle 27 6

The java based container configuration doesnt depend on doing a component scan in any way. Its merely a different approach for the XML based component configuration. With the XML configuration you'd just have to declare your bean with the MyServiceImpl class in case its already @inject annotated. Spring would recognize the annotations and take care of them. If you really want to instanciate MyServiceImpl from a @Configuration java class without calling the constructor yourself, then you'd have to make use of the bean factory (havent tested it, just give it a try):

@Configuration
public class MyConfiguration {

    @Autowired AutowireCapableBeanFactory beanFactory;

    @Bean public MyService myService() { 
        return beanFactory.createBean(MyServiceImpl.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true);
    }
}

I realise that the annotation config does not require a component scan but I wanted the autobuild functionality that the component scan uses. Your response led me to the piece of code responsible for autobuild. Thanks!

Spring annotations - @Configuration to invoke spring bean auto-buildin...

spring spring-annotations
Rectangle 27 6

The java based container configuration doesnt depend on doing a component scan in any way. Its merely a different approach for the XML based component configuration. With the XML configuration you'd just have to declare your bean with the MyServiceImpl class in case its already @inject annotated. Spring would recognize the annotations and take care of them. If you really want to instanciate MyServiceImpl from a @Configuration java class without calling the constructor yourself, then you'd have to make use of the bean factory (havent tested it, just give it a try):

@Configuration
public class MyConfiguration {

    @Autowired AutowireCapableBeanFactory beanFactory;

    @Bean public MyService myService() { 
        return beanFactory.createBean(MyServiceImpl.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true);
    }
}

I realise that the annotation config does not require a component scan but I wanted the autobuild functionality that the component scan uses. Your response led me to the piece of code responsible for autobuild. Thanks!

Spring annotations - @Configuration to invoke spring bean auto-buildin...

spring spring-annotations
Rectangle 27 121

The advantages and disadvantages of using this method

It is possible to migrate the xml to a @Configuration in a few steps:

Create a @Configuration annotated class:

@Configuration
public class MyApplicationContext {

}
  • For each <bean> tag create a method annotated with @Bean: @Configuration public class MyApplicationContext { @Bean(name = "someBean") public SomeClass getSomeClass() { return new SomeClassImpl(someInterestingProperty); // We still need to inject someInterestingProperty } @Bean(name = "anotherBean") public AnotherClass getAnotherClass() { return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse); // We still need to inject beanFromSomewhereElse } }

In order to import beanFromSomewhereElse we need to import it's definition. It can be defined in an XML and the we'll use @ImportResource:

@ImportResource("another-application-context.xml")
@Configuration
public class MyApplicationContext {
  ...  
}

If the bean is defined in another @Configuration class we can use the @Import annotation:

@Import(OtherConfiguration.class)
@Configuration
public class MyApplicationContext {
  ...
}

After we imported other XMLs or @Configuration classes, we can use the beans they declare in our context by declaring a private member to the @Configuration class as follows:

@Autowired
@Qualifier(value = "beanFromSomewhereElse")
private final StrangeBean beanFromSomewhereElse;

Or use it directly as parameter in the method which defines the bean that depends on this beanFromSomewhereElse using @Qualifier as follows:

@Bean(name = "anotherBean")
public AnotherClass getAnotherClass(@Qualifier (value = "beanFromSomewhereElse") final StrangeBean beanFromSomewhereElse) {
  return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse);
}

Importing properties is very similar to importing bean from another xml or @Configuration class. Instead of using @Qualifier we'll use @Value with properties as follows:

@Autowired
@Value("${some.interesting.property}")
private final String someInterestingProperty;

This can be used with SpEL expressions as well.

In order to allow spring to treat such classes as beans containers we need to mark this in our main xml by putting this tag in the context:

<context:annotation-config/>

You can now import @Configuration classes exactly the same as you would create a simple bean:

<bean class="some.package.MyApplicationContext"/>

There are ways to avoid spring XMLs altogether but they are not in the scope of this answer. You can find out one of these options in my blog post on which I'm basing my answer.

Basically I find this method of declaring beans much more comfortable than using XMLs due to a few advantages I see:

  • Typos - @Configuration classes are compiled and typos just won't allow compilations
  • Fail fast (compile time) - If you forget to inject a bean you'll fail on compile time and not on run-time as with XMLs
  • Easier to navigate in IDE - between constructors of beans to understand the dependency tree.

The disadvantages are not many as I see them but there are a few which I could think of:

  • With XMLs you can defined dependencies based on classes that are not available during compile time but are provided during run-time. With @Configuration classes you must have the classes available at compile time. Usually that's not an issue, but there are cases it may be.

Bottom line: It is perfectly fine to combine XMLs, @Configuration and annotations in your application context. Spring doesn't care about the method a bean was declared with.

One possible downsides is the loss of configuration. Say you have a class that mocks some functionality in development, then you want to swap it out for another class in the UAT environment. Using XML, then its just a matter of changing the config and allowing the application to run/restart. With these new class configurations, the classes would have to be recompiled.

@JoseChavez - That's a great argument that I've already heard a couple of times. And I tried to do some statistic research in which I couldn't find any app or system that uses XMLs outside of its jars/wars. The practical meaning of it is that you need to either unzip the jar and change the XML (which I couldn't find anybody who does that) or rebuild your jars (which is what everyone I talked to said they've done so far). So, bottom line - as it may be a considerable argument, it's usually not important in real life.

That's what @Profile annotation, and the "${env.value}" syntax, are for. With @Profile("someName") you can tag an entire configuration for use only when the profile is active. In your application.properties (or .yml) file, then you may set spring.profiles.active=someName,default... To set it dynamically based on environment variables, use the ${SOME_ENV_VAR} syntax as the value for spring.active.profiles and set the environment variable. Spring now recommends using java config - docs.spring.io/spring-boot/docs/current/reference/htmlsingle/

java - Converting spring XML file to spring @Configuration class - Sta...

java spring configuration autowired
Rectangle 27 121

The advantages and disadvantages of using this method

It is possible to migrate the xml to a @Configuration in a few steps:

Create a @Configuration annotated class:

@Configuration
public class MyApplicationContext {

}
  • For each <bean> tag create a method annotated with @Bean: @Configuration public class MyApplicationContext { @Bean(name = "someBean") public SomeClass getSomeClass() { return new SomeClassImpl(someInterestingProperty); // We still need to inject someInterestingProperty } @Bean(name = "anotherBean") public AnotherClass getAnotherClass() { return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse); // We still need to inject beanFromSomewhereElse } }

In order to import beanFromSomewhereElse we need to import it's definition. It can be defined in an XML and the we'll use @ImportResource:

@ImportResource("another-application-context.xml")
@Configuration
public class MyApplicationContext {
  ...  
}

If the bean is defined in another @Configuration class we can use the @Import annotation:

@Import(OtherConfiguration.class)
@Configuration
public class MyApplicationContext {
  ...
}

After we imported other XMLs or @Configuration classes, we can use the beans they declare in our context by declaring a private member to the @Configuration class as follows:

@Autowired
@Qualifier(value = "beanFromSomewhereElse")
private final StrangeBean beanFromSomewhereElse;

Or use it directly as parameter in the method which defines the bean that depends on this beanFromSomewhereElse using @Qualifier as follows:

@Bean(name = "anotherBean")
public AnotherClass getAnotherClass(@Qualifier (value = "beanFromSomewhereElse") final StrangeBean beanFromSomewhereElse) {
  return new AnotherClassImpl(getSomeClass(), beanFromSomewhereElse);
}

Importing properties is very similar to importing bean from another xml or @Configuration class. Instead of using @Qualifier we'll use @Value with properties as follows:

@Autowired
@Value("${some.interesting.property}")
private final String someInterestingProperty;

This can be used with SpEL expressions as well.

In order to allow spring to treat such classes as beans containers we need to mark this in our main xml by putting this tag in the context:

<context:annotation-config/>

You can now import @Configuration classes exactly the same as you would create a simple bean:

<bean class="some.package.MyApplicationContext"/>

There are ways to avoid spring XMLs altogether but they are not in the scope of this answer. You can find out one of these options in my blog post on which I'm basing my answer.

Basically I find this method of declaring beans much more comfortable than using XMLs due to a few advantages I see:

  • Typos - @Configuration classes are compiled and typos just won't allow compilations
  • Fail fast (compile time) - If you forget to inject a bean you'll fail on compile time and not on run-time as with XMLs
  • Easier to navigate in IDE - between constructors of beans to understand the dependency tree.

The disadvantages are not many as I see them but there are a few which I could think of:

  • With XMLs you can defined dependencies based on classes that are not available during compile time but are provided during run-time. With @Configuration classes you must have the classes available at compile time. Usually that's not an issue, but there are cases it may be.

Bottom line: It is perfectly fine to combine XMLs, @Configuration and annotations in your application context. Spring doesn't care about the method a bean was declared with.

One possible downsides is the loss of configuration. Say you have a class that mocks some functionality in development, then you want to swap it out for another class in the UAT environment. Using XML, then its just a matter of changing the config and allowing the application to run/restart. With these new class configurations, the classes would have to be recompiled.

@JoseChavez - That's a great argument that I've already heard a couple of times. And I tried to do some statistic research in which I couldn't find any app or system that uses XMLs outside of its jars/wars. The practical meaning of it is that you need to either unzip the jar and change the XML (which I couldn't find anybody who does that) or rebuild your jars (which is what everyone I talked to said they've done so far). So, bottom line - as it may be a considerable argument, it's usually not important in real life.

That's what @Profile annotation, and the "${env.value}" syntax, are for. With @Profile("someName") you can tag an entire configuration for use only when the profile is active. In your application.properties (or .yml) file, then you may set spring.profiles.active=someName,default... To set it dynamically based on environment variables, use the ${SOME_ENV_VAR} syntax as the value for spring.active.profiles and set the environment variable. Spring now recommends using java config - docs.spring.io/spring-boot/docs/current/reference/htmlsingle/

java - Converting spring XML file to spring @Configuration class - Sta...

java spring configuration autowired
Rectangle 27 2

One possible option is to use Spring Profiles (@Profile). Based on profile you configured in configuration file or pass into project via system property, you can activate or deactivate beans.

Is the beauty of Spring DI -resolving dependences at run-time instead ...

java spring dependency-injection spring-ioc
Rectangle 27 27

After reading some related posts here and having further discussion in the team we come to the following conclusions. I hope the would be useful to others here.

About XML configuration (which we are using up to now), we decided to keep it for dependencies that are for libraries (being either developed by us, or by third parties). Libraries by definition should provide certain functionality only and can be used in various scenarios, which may not always involve DI. Therefore using annotations in our library projects will bring dependencies of the DI framework (Spring in our case) to the library, and this would be useless when the library is used without DI. Having extra dependencies is not considered a good practice among our team (an in general IMHO). When we are assembling an application, the application has the needed DI dependencies and the injection of library classes is done by configuration. XML is also good for providing mock implementations for many components, without recompiling the modules that will use them. This gives us flexibility when testing or running in local or production environment.

About annotations, we actually decided that we can benefit using them when the injected components will not vary, t.e. there will not be scenarios where different implementations of a component would be used. We decided that annotations will be very useful for small modules/applications with clear functionality, that will not change or support different implementations. Such modules we can almost use out of the box in different projects, without writing the tedious XML. However, we agreed that these modules should have the dependencies described in our technical documentation, so that when assembling the entire application, one can have an idea of these dependencies without scrolling through the code, or even loading the module in the IDE. Still, it seems that annotations will require the module to be somewhat mature about what dependencies it will use. This is also applicable for the java class configurations, which is the modern Spring alternative of XML contexts.

In general if our dependencies may vary for different scenarios, or a module can be used with different components, we decided to keep the XML and not to hard-code any dependencies in such module. Clearly, there MUST be a right balance between both approaches, and a clear idea for the usages.

An important update regarding the mixed approach. Recently we had a case with a test framework we created for our QA team, which required dependencies from another project. The framework was designed to use the annotation approach and Spring configuration classes, while the referenced project has some xml contexts that we needed to reference. Unfortunately, the test classes (we used org.testng with spring support) could only work with either xml or java configuration classes, not both.

This situation illustrates a case where both approaches would clash and clearly, one must be discarded. In our case, we migrated the test framework to use spring xml contexts, but other uses could imply the other way around.

java - Spring annotation-based DI vs xml configuration? - Stack Overfl...

java spring configuration dependency-injection annotations
Rectangle 27 25

After reading some related posts here and having further discussion in the team we come to the following conclusions. I hope the would be useful to others here.

About XML configuration (which we are using up to now), we decided to keep it for dependencies that are for libraries (being either developed by us, or by third parties). Libraries by definition should provide certain functionality only and can be used in various scenarios, which may not always involve DI. Therefore using annotations in our library projects will bring dependencies of the DI framework (Spring in our case) to the library, and this would be useless when the library is used without DI. Having extra dependencies is not considered a good practice among our team (an in general IMHO). When we are assembling an application, the application has the needed DI dependencies and the injection of library classes is done by configuration. XML is also good for providing mock implementations for many components, without recompiling the modules that will use them. This gives us flexibility when testing or running in local or production environment.

About annotations, we actually decided that we can benefit using them when the injected components will not vary, t.e. there will not be scenarios where different implementations of a component would be used. We decided that annotations will be very useful for small modules/applications with clear functionality, that will not change or support different implementations. Such modules we can almost use out of the box in different projects, without writing the tedious XML. However, we agreed that these modules should have the dependencies described in our technical documentation, so that when assembling the entire application, one can have an idea of these dependencies without scrolling through the code, or even loading the module in the IDE. Still, it seems that annotations will require the module to be somewhat mature about what dependencies it will use. This is also applicable for the java class configurations, which is the modern Spring alternative of XML contexts.

In general if our dependencies may vary for different scenarios, or a module can be used with different components, we decided to keep the XML and not to hard-code any dependencies in such module. Clearly, there MUST be a right balance between both approaches, and a clear idea for the usages.

An important update regarding the mixed approach. Recently we had a case with a test framework we created for our QA team, which required dependencies from another project. The framework was designed to use the annotation approach and Spring configuration classes, while the referenced project has some xml contexts that we needed to reference. Unfortunately, the test classes (we used org.testng with spring support) could only work with either xml or java configuration classes, not both.

This situation illustrates a case where both approaches would clash and clearly, one must be discarded. In our case, we migrated the test framework to use spring xml contexts, but other uses could imply the other way around.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

java - Spring annotation-based DI vs xml configuration? - Stack Overfl...

java spring configuration dependency-injection annotations