java依赖注入

iibxawm4  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(361)

如果我有下面的两个类,我们可以看到这是somebean的构造函数注入,但是somebean中的构造函数只有带有参数“stringwords”的构造函数,那么在依赖项注入期间,我们如何为依赖项的构造函数指定参数?

@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();
        }
}
u5rb5r59

u5rb5r591#

您应该将somebean类型的bean添加到spring配置类中。
具有所需bean的此类示例:

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

m2xkgtsf2#

对于基于java的配置:

@Configuration 
public class SpringAppConfiguration {

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

对于xml配置:

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

查看此快速指南:https://www.baeldung.com/constructor-injection-in-spring

相关问题