Program-Me-Rev Program-Me-Rev - 18 days ago 7
Java Question

How to pass class constructor parameters in Spring bean Autowired by annotations

The normal way without IOC containers would be:

new User("Names", 22);


where the parameter values here are dynamic, whereby, for example, they are fetched via a user submission form, thereby can't be stored in a file.

TextField userNames = new TextField();

names = userNames.getText()


same for the other parameters.

where:

@Component
public class User {
public User(String names, int age) {
.
.
.
}
}


How do I initialize
User
, while passing the constructor's parameters, where User is
Autowired
into another class:

@Component
public class AnotherClass {
@Autowired
User user(....)????? // How do I do it here
.
.
.
}

Answer

I doubt that is what you really want to do. My guess is that User is some kind of model object that should not be handled by Spring's dependency injection.

Dependency injection (which is greatly explained here) creates and wires beans together typically when the container is started or for Spring MVC when a request is executed. The User object must therefore be created before the instance of AnotherClass is created.

If this is part of a request using Spring MVC the @ModelAttribute together with @RequestParam and @PathVariable are likely to be your friends. For some great documentation of this please check the Spring docs

Comments