[java] Are all Spring Framework Java Configuration injection examples buggy?

I'm wondering if it's only me or are most examples of Spring's Java Configuration flawed? Like here for example:

http://spring.io/blog/2008/03/27/spring-java-configuration-what-s-new-in-m3 http://spring.io/blog/2013/07/18/javaconfig-support-in-the-spring-tool-suite

Notice how they inject beans? They use methods directly, like: new OrderRepository(dataSource()) here:

@Configuration public class ApplicationConfig {      public @Bean OrderRepository orderRepository() {         return new OrderRepository(dataSource());     }      public @Bean DataSource dataSource() {         // instantiate and return an new DataSource ...     } } 

This got me thinking - wouldn't it create two objects if used twice? Effectively bypassing singleton guarantee of Spring? Why aren't they injecting beans instead? As dependency framework was designed to work in the first place.

Let's do a quick test. Take those two classes for example - TestParent and TestedChild. Parent accepts a child: new TestParent(new TestedChild()). We will make them singleton beans in a minute.

public class TestedChild { }  public class TestParent {      private TestedChild child;      public TestParent(TestedChild child) {         this.child = child;     }      public TestedChild getChild() { return child; }  } 

What I want to see is if we can in fact get two different instances of TestedChild created during context initialization. Let's configure our singleton beans now:

@Configuration public class TestInjectionConfig {      @Bean(name = "injected")     public TestParent injected(TestedChild bean) {         return new TestParent(bean);     }      @Bean(name = "direct")     public TestParent direct() {         return new TestParent(testedBean());     }      @Bean     public TestedChild testedBean() {         return new TestedChild();     }  } 

I'm creating two different TestParent objects which should have the same TestedChild injected at the time of their creation.

Let's test them:

@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TestInjectionConfig.class) public class InjectionApplicationTest {      @Inject @Named("injected")     TestParent injected;      @Inject @Named("direct")     TestParent direct;      @Test     public void instancesShouldBeTheSame() {          Assert.assertSame(injected, direct);      }  } 

I would expect the beans to be the same but this is what I'm getting on Spring 3.2.6:

junit.framework.AssertionFailedError: expected same:<pl.aie.TestParent@59e5a42c> was not:<pl.aie.TestParent@737d72cf> 

Back to the question. Why are the examples using direct method calls on Spring configuration classes? And if they are meant to be called like that, why are they annotated with a @Bean annotation? Is it a bad practice or is my logic/code flawed somewhere?

This question is related to java spring dependency-injection spring-java-config

The answer is


In your test, you are comparing the two TestParent beans, not the single TestedChild bean.

Also, Spring proxies your @Configuration class so that when you call one of the @Bean annotated methods, it caches the result and always returns the same object on future calls.

See here:


Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with spring tag:

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type No String-argument constructor/factory method to deserialize from String value ('') Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException Read file from resources folder in Spring Boot RestClientException: Could not extract response. no suitable HttpMessageConverter found The origin server did not find a current representation for the target resource or is not willing to disclose that one exists The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat Spring boot: Unable to start embedded Tomcat servlet container Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start 'Field required a bean of type that could not be found.' error spring restful API using mongodb java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Unsupported Media Type in postman Configure active profile in SpringBoot via Maven How does spring.jpa.hibernate.ddl-auto property exactly work in Spring? MultipartException: Current request is not a multipart request Consider defining a bean of type 'service' in your configuration [Spring boot] UnsatisfiedDependencyException: Error creating bean with name How Spring Security Filter Chain works Spring Boot Java Config Set Session Timeout What is the recommended project structure for spring boot rest projects? Spring @Autowired and @Qualifier Spring security CORS Filter 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE how to use Spring Boot profiles Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Check date between two other dates spring data jpa How to beautifully update a JPA entity in Spring Data? How do I activate a Spring Boot profile when running from IntelliJ? Spring-boot default profile for integration tests Unable to find a @SpringBootConfiguration when doing a JpaTest Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET) Spring Boot @Value Properties Where is the application.properties file in a Spring Boot project? How to return a html page from a restful controller in spring boot? How to set Spring profile from system variable? How to POST form data with Spring RestTemplate? Spring Data and Native Query with pagination Spring Resttemplate exception handling Spring Boot - Loading Initial Data Pass multiple parameters to rest API - Spring org.springframework.web.client.HttpClientErrorException: 400 Bad Request

Questions with dependency-injection tag:

Are all Spring Framework Java Configuration injection examples buggy? Passing data into "router-outlet" child components ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why? org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController' How to inject window into a service? How to get bean using application context in spring boot Resolving instances with ASP.NET Core DI from within ConfigureServices How to inject a Map using the @Value Spring Annotation? WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default Explain why constructor inject is better than other options Spring JUnit: How to Mock autowired component in autowired component exclude @Component from @ComponentScan Dependency injection with Jersey 2.0 AngularJS: Service vs provider vs factory Why does one use dependency injection? Passing Parameters JavaFX FXML Spring: Why do we autowire the interface and not the implemented class? Spring expected at least 1 bean which qualifies as autowire candidate for this dependency One DbContext per web request... why? Symfony 2 EntityManager injection in service Requested bean is currently in creation: Is there an unresolvable circular reference? spring autowiring with unique beans: Spring expected single matching bean but found 2 What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition? Inversion of Control vs Dependency Injection What is javax.inject.Named annotation supposed to be used for? How do the major C# DI/IoC frameworks compare? @Resource vs @Autowired Using Spring 3 autowire in a standalone Java application Why use @PostConstruct? What is Dependency Injection? Why is IoC / DI not common in Python? Injecting Mockito mocks into a Spring bean Why do I need an IoC container as opposed to straightforward DI code? Can someone explain Microsoft Unity? Dependency Injection vs Factory Pattern How can I inject a property value into a Spring Bean which was configured using annotations? Which .NET Dependency Injection frameworks are worth looking into?

Questions with spring-java-config tag:

Are all Spring Framework Java Configuration injection examples buggy? disabling spring security in spring boot app How To Inject AuthenticationManager using Java Configuration in a Custom Filter