首页 > 解决方案 > @Bean List 在实现类中不起作用

问题描述

我在 Config 类的 @Bean 中有 List:

@Configuration
public class Config {

    @Bean
    public List<IBeer> beers(){
        List<IBeer> beers = new ArrayList<IBeer>();
        beers.add(new Warka("Warka", 4.5, 3.20));
        return beers;
    }
}

...我正在尝试将此 Bean 注入此实现:

public class Order implements IOrder {

    @Value("#{beers[0]}")
    private IBeer beer;

    @Autowired
    private List<IBeer> beers;

    public Order (IBeer beer) {
        super();
        this.beer = beer;
    }

    public void showOrder() {
        System.out.printf("nazwa: " + beer.getName() + "%n" +
               "procenty: " + beer.getAlcoholPercentage() + "%%" + "%n" +
               "cena: " + beer.getPrice() + "PLN" + "%n");
    }

    }

Warka 类只有构造函数(字符串、双精度、双精度)和 3 个 getter,它实现接口 IBeer。类 Order 实现接口 IOrder。

它不应该工作吗?我的项目在这里: https ://github.com/dadziu/nawalmySie/tree/sec

wrz 20, 2018 5:34:47 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@4fe3c938: startup date [Thu Sep 20 17:34:47 CEST 2018]; root of context hierarchy
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1 (file:/C:/Users/Dadziu/.m2/repository/org/springframework/spring-core/5.0.8.RELEASE/spring-core-5.0.8.RELEASE.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'pl.nawalmySie.implementation.Order' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:346)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:333)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1107)
at pl.nawalmySie.app.App.main(App.java:14)

Process finished with exit code 1

标签: spring

解决方案


推荐阅读