DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Dependency Injection in Spring
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • How Stalactite ORM Implements Its Fluent DSL
  • Mastering Spring: Synchronizing @Transactional and @Async Annotations With Various Propagation Strategies

Trending

  • MCP Servers: The Technical Debt That Is Coming
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • Secure by Design: Modernizing Authentication With Centralized Access and Adaptive Signals
  • Kullback–Leibler Divergence: Theory, Applications, and Implications
  1. DZone
  2. Coding
  3. Frameworks
  4. Defining Bean Dependencies With Java Config in Spring Framework

Defining Bean Dependencies With Java Config in Spring Framework

Here's how to declare beans via Java Config, ranging from inter-bean references to using dependencies as method parameters.

By 
Bartłomiej Słota user avatar
Bartłomiej Słota
·
Jul. 19, 17 · Tutorial
Likes (23)
Comment
Save
Tweet
Share
163.6K Views

Join the DZone community and get the full member experience.

Join For Free

I found it hard to choose a topic to describe in my first blog post. I wanted it not to be too trivial, nor too complicated It turned out that there are many basic concepts in Spring Framework that can be confusing. Java-based configuration is one of them. I hear my colleagues asking from time to time about it, and I see numerous questions regarding it on StackOverflow. Nevermind the motivation, below you will find a compact description of how to declare beans with Java Config.

Please note that this post won't cover bean dependencies of different scopes nor discussion on annotations like @Component, @Service, @Repository, etc., that are often a good alternative to the described approach. Java Config might seem to be overkill in many situations, but I hope you will find the post useful anyway. Let's go!

Inter-Bean References

Imagine we have the following repository:

public class MyRepository {
    public String findString() {
        return "some-string";
    }
}


And a service that depends on a repository of that type:

public class MyService {
    private final MyRepository myRepository;

    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

    public String generateSomeString() {
        return myRepository.findString() + "-from-MyService";
    }
}


The first solution is pretty straightforward, and it's called inter-bean reference. The MyService  bean depends on MyRepository. In order to fulfill this dependency, we pass the myRepository()  method as a constructor parameter (constructor injection).

@Configuration
class MyConfiguration {
    @Bean
    public MyService myService() {
        return new MyService(myRepository());
    }

    @Bean
    public MyRepository myRepository() {
        return new MyRepository();
    }
}


Easy, right? Good, let's complicate it a bit. Imagine we have the following repository, which has a few dependencies. To make it clearer, I will use String fields:

public class MyRepository {
    private final String prefix;
    private final String suffix;

    public MyRepository (String prefix, String suffix) {
        this.prefix = prefix;
        this.suffix = suffix;
    } 

    public String findString() {
        return prefix + "-some-string-" + suffix;
    }
}


MyService stays the same. Now we want to create a singleton bean of type MyRepository, where the prefix and suffix are values from an external properties file. In order to inject those properties, we will use the @Value annotation.

@Configuration
class MyConfiguration {
    @Bean
    public MyService myService() {
        return new MyService(myRepository(null, null));
    }

    @Bean
    public MyRepository myRepository(@Value("${repo.prefix}") String prefix,
                                     @Value("${repo.suffix}") String suffix) {
        return new MyRepository(prefix, suffix);
    }
}


Wait, what did I just do? I did a constructor injection with a method having both params equal to null. Here is how it all works: The @Configuration annotation tells Spring that so-annotated class will have one or more beans defined inside. The @Bean annotation is a way of telling the Spring container to manage the bean returned by that so-annotated method. Like in the examples above, the @Bean methods are generally used inside configuration classes, which are proxied by CGLIB — the result of the bean-defining method is registered as a Spring bean, and each call of this method will return the same bean (as long as it is a singleton of course). Thus, thanks to CGLIB, whatever params you use while calling such methods (like nulls in the example above), you will get the proper bean. Remember also that according to CGLIB usage, configuration classes and bean-defining methods must not be private or final.

There is a caveat, though. The @Bean annotation might be used not only in @Configuration  classes — it can be used in @Component, for example. Then we are talking about a so-called Lite mode. In this case. there are no proxies created, so method invocations are not intercepted and thus interpreted as a typical Java method invocation.

I think that an inter-bean reference is a very nice way of defining bean dependencies inside a @Configuration class as long as the bean-defining method has no parameters. Otherwise, I go with the option below — read on!

Dependencies as @Bean Method Parameters

Okay, and what if you don't like passing methods as arguments? Or you have a MyRepository bean defined with a @Component annotation or in some other @Configuration class (but of course in the same context)? It is enough to put your dependency as a method parameter (@Autowired is not needed!):

@Configuration
class MyConfiguration {
    @Bean
    public MyService myService(MyRepository myRepository) {
        return new MyService(myRepository);
    }
}


But, hold on — what if I have several MyRepository beans? Aha! Spring firstly looks at the type of parameter. If it finds more than one bean of this type, it tries to inject by name (yes, the name of the parameter must match the bean name):

@Configuration
class MyConfiguration {

    @Bean
    public MyRepository myFirstRepository() {
        return new MyRepository("first", "repository");
    }

    //a bean that will be injected by name into myService
    @Bean
    public MyRepository mySecondRepository() {
        return new MyRepository("second", "repository");
    }

    @Bean
    public MyService myService(MyRepository mySecondRepository) {
        return new MyService(myRepository);
    }
}


If you don't want to base it on parameter name, you can use the @Qualifier annotation as well, and it will take precedence over the parameter name:

@Configuration
class MyConfiguration {

    //a bean that will be injected by name into myService
    @Bean
    public MyRepository myFirstRepository() {
        return new MyRepository("first", "repository");
    }

    @Bean
    public MyRepository mySecondRepository() {
        return new MyRepository("second", "repository");
    }

    @Bean
    public MyService myService(@Qualifier("myFirstRepository") MyRepository someRepository) {
        return new MyService(someRepository);
    }
}


@Configuration Composition

You may now wonder what to do when you have configuration spread over numerous @Configuration classes and you want to set dependencies among them. Let's consider the following classes:

@Configuration
class FirstConfiguration {
    @Bean
    public FirstService firstService() {
        return new FirstService();
    }
}
@Configuration
class SecondConfiguration {
    @Bean
    public SecondService secondService() {
        return new SecondService();
    }
}


Now imagine that SecondService becomes dependent on FirstService. If both configurations are settled in a common application context (this is important here!), you can inject the bean like in one of the previous examples:

@Configuration
class SecondConfiguration {
    @Bean
    public SecondService secondService(FirstService firstService) {
        return new SecondService(firstService);
    }
}


@Configuration is meta-annotated with @Component, which means that the class will be component scanned and you can benefit from the DI concepts brought in by Spring. It means you can also autowire your bean this way:

@Configuration
class SecondConfiguration {
    @Autowired
    private FirstService firstService;

    @Bean
    public SecondService secondService() {
        return new SecondService(firstService);
    }
}


As I mentioned before, @Configuration is a @Component. Thus, you can inject it as if it is a regular bean and call its methods in order to retrieve beans (you will inject a CGLIB proxy!).

@Configuration
class SecondConfiguration {
    @Autowired
    private FirstConfiguration firstConfiguration;

    @Bean
    public SecondService secondService() {
        return new SecondService(firstConfiguration.firstService());
    }
}


That's not all. There is yet another Spring mechanism hidden under the @Import annotation:

@Configuration
@Import({FirstConfiguration.class})
class SecondConfiguration {
    ...
}


This looks nice and gives you the ability to relate different configurations that are not necessarily under the same context scope. In this setup, you can use the autowiring of beans and the configuration class as well (see the two previous code snippets).

Conclusions

Defining bean dependencies is a very basic concept of Spring Framework, but as you could see here, there are lots of possibilities to do it, and there are enough approaches to get confused. Which to choose, which is the best, which looks nice, and which is ugly — it depends on the situation and personal (or team) preferences. How do I do it?

  • When I have bean definitions inside one configuration class, and bean-definig methods have no parameters, I use inter-bean references. Otherwise, I choose passing a bean as a method parameter. Easy IDE navigation is not as vital as good-looking code.
  • When I have two @Configuration classes inside a common context, I pass beans as method paremeters or autowire them.
  • When I have two @Configuration classes in separate contexts, I use an @Import annotation and I pass beans as method paremeters or autowire them.
Spring Framework Dependency Java (programming language) Framework Annotation

Published at DZone with permission of Bartłomiej Słota, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Dependency Injection in Spring
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • How Stalactite ORM Implements Its Fluent DSL
  • Mastering Spring: Synchronizing @Transactional and @Async Annotations With Various Propagation Strategies

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!