简体   繁体   中英

Java Dependency Injection with parameters

if I have the two classes below as we could see this is a constructor injection for SomeBean, however the constructor in SomeBean only has the constructor with parameter "String words", so during the dependency injection how do we specify the parameter for the constructor of the dependency?

@Component
public class SomeBean {
    private String words;

    public SomeBean(String words) {
        this.words = words;
    }

    public String getWords() {
        return words;
    }

    public void setWords(String words) {
        this.words = words;
    }

    public void sayHello(){
        System.out.println(this.words);
    }
}

@Service
public class MapService {
        private SomeBean someBean;

        @Autowired
        public MapService(SomeBean someBean) {
                this.someBean = someBean;
        }

        public MapService() {

        }

        public void sayHello(){
                this.someBean.sayHello();
        }
}

You should add a Bean of the SomeBean type to a Spring configuration class.

Example of such class with the required Bean:

@Configuration 
public class Config {
    @Bean
    public SomeBean someBean() {
         return new SomeBean("words");
    }
}

For Java based configuration:

@Configuration 
public class SpringAppConfiguration {

    @Bean
    public SomeBean someBean() {
         return new SomeBean("value");
    }
}

For XML configuration:

<bean id="someBean" class="package.SomeClass">
    <constructor-arg index="0" value="some-value"/>
</bean>

Check this quick guide: https://www.baeldung.com/constructor-injection-in-spring

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