Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Encapsulate a Spring Bean

DZone's Guide to

How to Encapsulate a Spring Bean

· Java Zone ·
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

As far as I know the Spring Framework doesn’t provide any mechanism to encapsulate Spring beans other than having separate contexts. So when you have public class registered in Spring’s Inversion of Control container, it can be autowired in any Spring bean from same context configuration. This is very powerful but it is also very dangerous. Developers can easily couple beans together. With lack of discipline team can easily shoot themselves in foot. Unfortunately I was working on one monolithic project where team was shooting themselves into foot with submachine gun. Wiring was breaking layering rules often. Nobody could easily follow what is dependent on what. Bean dependency graph was just crazy. This is serious concern in bigger applications.

Luckily there is one simple way how to encapsulate Spring bean. Spring works nicely with default access modifier on class level. So you can create package private bean, which can be used only within current package. Simple and powerful. Let’s take a look at example:

package net.lkrnac.blog.spring.encapsulatebean.service;
 
import org.springframework.stereotype.Service;
 
@Service
class AddressService {
    public String getAddress(String userName){
        return "3 Dark Corner";
    }
}

This simple bean is wired into another one within same package:

package net.lkrnac.blog.spring.encapsulatebean.service;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
@Service
public class UserService {
    private AddressService addressService;
 
    @Autowired
    public UserService(AddressService addressService) {
        this.addressService = addressService;
    }
     
    public String getUserDetails(String userName){
        String address = addressService.getAddress(userName);
        return String.format("User: %s, %s", userName, address);
    }
}

Main context just scans both beans:

package net.lkrnac.blog.spring.encapsulatebean;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
}

Here is test to prove it works fine:

package net.lkrnac.blog.spring.encapsulatebean;
 
import net.lkrnac.blog.spring.encapsulatebean.service.UserService;
 
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class ApplicationTests {
    @Autowired
    private UserService userService;
     
    @Test
    public void isPackagePrivateBeanCalled(){
        //GIVEN - spring context defined by Application class
         
        //WHEN
        String actualUserDetails = userService.getUserDetails("john");
         
        //THEN
        Assert.assertEquals("User: john, 3 Dark Corner", actualUserDetails);
    }
}

I believe everybody should consider using default access modifier for every new bean. Obviously there would need to be some public bean within each package. But at not every bean. Source code is on GitHub.

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}