Setter-Based DI in Spring

Setter-Based DI

For setter-based DI, the container will call setter methods of our class after invoking a no-argument constructor or no-argument static factory method to instantiate the bean.

# Setter-Based DI
@Bean
public Store store() {
    
    
    Store store = new Store();
    store.setItem(new item1());
    return store;
}

# use XML
<bean id="store" class="org.baeldung.store.Store">
    <property name="item" ref="item1" />
</bean>

Constructor-Based DI 和 Setter-Based DI 可以组合使用
Constructor-Based DI :强制性的依赖,即刚需( mandatory dependencies
Setter-Based DI :可有可无,即可选( optional dependencies


参考:
Intro to Inversion of Control and Dependency Injection with Spring

猜你喜欢

转载自blog.csdn.net/weixin_37646636/article/details/133325256