rakesh mehra
rakesh mehra

Reputation: 642

Spring constructor injection using java config

I have a Class that accepts the following constructor

    public Student(int id, String name, Map<String, List<String>> mapInject) {
    super();
    this.id = id;
    this.name = name;
    this.mapInject = mapInject;
}

And from spring Java Config, I am injecting the constructor args like below..

@Configuration
public class JavaConfig {

@Bean
public Employee getEmployeeBean() {

    Map<String,List<String>> mapInject = new HashMap<String,List<String>>();

    //Add map element

    return new Employee(3123,"John",mapInject);
}
}

Am i doing constructor injection here? Is this the right way to do so?

Upvotes: 1

Views: 1915

Answers (1)

Markoorn
Markoorn

Reputation: 2565

I wouldn't use Spring to handle this bean creation, unless you want ALL employees to have the same id and name which I doubt.

The power behind Spring is its Dependency Injection (DI) where you define beans for providers such as database managers, services, etc. and inject those into your components. Defining a @Bean like you have there serves no purpose as now you can only inject employees with an id of 3123 and name John.

It's important to understand that just because you are using Spring it doesn't mean EVERYTHING needs to be handled as a bean - you will always need standard POJOs for housing and passing around state (such as your Employee class) which doesn't need to have anything to do with Spring.

Down the line you might have an EmployeeService for example which houses business logic to fetch employees from a database or something, this could then be configured as a bean so it can be injected across the application.

EDIT

@Configuration
public class JavaConfig {

    @Bean
    @Autowired //assuming a sessionfactory been is configured elsewhere 
    public EmployeeService employeeService(final SessionFactory sessionfactory) {
        return new EmployeeService(sessionFactory);
    }
}

You could then inject this anywhere (maybe in a controller for example):

@RestController
public class EmployeeController {
    private final EmployeeService employeeService;

    @Autowired
    public EmployeeController(final EmployeeService employeeService) {
         this.employeeService = employeeService;
    }
}

Where the EmployeeController doesn't need to know or care that the userService has a DB connection and doesn't need to worry about configuring it as Spring will handle all of that.

Upvotes: 2

Related Questions