相关疑难解决方法(0)

究竟什么是Field Injection以及如何避免它?

我在一些帖子中读过,Spring MVCPortlets建议不要进行现场注射.因为我试图得到一个所以我问自己我是否使用现场注射,我无法回答它.据我所知场注入是,如果你注入一个Bean与一个属性@Autowired是这样的:

CartController.java:

...
@Autowired
private Cart cart;
...
Run Code Online (Sandbox Code Playgroud)

BookshopConfiguartion.java:

@Configuration
public class BookShopConfiguration {

@Bean
public Cart cart(){
    return new Cart();
}
//more configuration
Run Code Online (Sandbox Code Playgroud)

Cart.java习惯于在购物车中存储和提供有关书籍的信息.

在我的研究期间,我读到了构造函数注入:

MyComponent.java:

...
public class MyComponent{
private Cart cart;

@Autowired
public MyComponent(Cart cart){
   this.cart = cart;
}
...
Run Code Online (Sandbox Code Playgroud)

这两种注射的优点和缺点是什么?


编辑1:由于此问题被标记为此问题的重复,我检查了它.因为在问题和答案中都没有任何代码示例,我不清楚我是否正确猜测我正在使用哪种注射类型.

java portlet dependency-injection spring-mvc autowired

90
推荐指数
3
解决办法
5万
查看次数

Spring无法自动装配,有多个``类型的bean

这是我的问题:我有一个基本接口和两个实现类.

Service类对基接口有依赖关系,代码如下:

@Component
public interface BaseInterface {}
Run Code Online (Sandbox Code Playgroud)
@Component
public class ClazzImplA implements  BaseInterface{}
Run Code Online (Sandbox Code Playgroud)
@Component
public class ClazzImplB implements  BaseInterface{}
Run Code Online (Sandbox Code Playgroud)

配置是这样的:

@Configuration
public class SpringConfig {
    @Bean
    public BaseInterface clazzImplA(){
        return new ClazzImplA();
    }

    @Bean
    public BaseInterface clazzImplB(){
        return new ClazzImplB();
    }
}
Run Code Online (Sandbox Code Playgroud)

服务类依赖于基接口将决定通过某些业务逻辑自动装配哪个实现.代码如下:


@Service
@SpringApplicationConfiguration(SpringConfig.class)
public class AutowiredClazz {
    @Autowired
    private BaseInterface baseInterface;

    private AutowiredClazz(BaseInterface baseInterface){
        this.baseInterface = baseInterface;
    }
}
Run Code Online (Sandbox Code Playgroud)

并且IDEA抛出异常:无法自动装配.有多个BaseInterface类型的bean .

虽然可以通过@ Qualifier来解决,但在这种情况下我无法选择依赖类.

@Autowired
@Qualifier("clazzImplA")
private BaseInterface baseInterface;
Run Code Online (Sandbox Code Playgroud)

我试着阅读弹簧文档并提供了一个,Constructor-based dependency injection但我仍然对这个问题感到困惑.

谁能帮我 ?

java spring

15
推荐指数
2
解决办法
2万
查看次数