简体   繁体   中英

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
    .
    .
    .
}

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

public User(  @Value("Ganesh") String names,               
@Value("27")  int age) {
names=names;
this.age=age;
}

Other than @value, using index in XML also comes with flexibility, if index=0, say, is used two times, the later value is used to overwrite the older value. Similarly, type can be specified in case of overloaded and parametrised constructors and the IOC takes care by itself to select the appropriate constructor. If type or index are not provided, the default order of constructor args is considered and if the parametrised cons does not match, it gIves exception. Suppose, setters are used and inside the bean tag, two property tags are provided for same name, in that case, exception is thrown instead of overriding the value. In setters two parameters are not allowed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM