使用从应用程序属性填充的 Hashmap 自动装配 bean 不起作用

Autowiring bean with Hashmap populated from application properties not working

我想将 Hashmap 的值从 Spring 引导应用程序传递到 CLI。我收到空指针异常。请让我知道这里出了什么问题?

申请Class

@SpringBootApplication
@ComponentScan(basePackages = { "com.xyz.movie*"})
public class Application  implements CommandLineRunner{
@Autowired
private Environment environment;
@Autowired
ApplicationContext context;

@Autowired
MovieCollections movieCollections;

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

@Override
public void run(String... arg0) throws Exception {
    try {
        Customer customer = new Customer();
    //  MovieCollections collections = (MovieCollections) context.getBean("movieCollections");
        Scanner sc = new Scanner(System.in);
        if(movieCollections==null) {
            System.out.println("it is null");
        }
        else
        {
            System.out.println("it is NOT null");
            System.out.println(movieCollections.getMovieCollectionMap());
        }

        System.out.println("Select Movie: ");
        **// NULL POINTER  HERE**
        for(String s:movieCollections.getMovieCollectionMap().values()) {
            System.out.println(s);
        }

电影收藏Class

@EnableConfigurationProperties
@PropertySource(value ="application.properties")
@ConfigurationProperties(prefix="movies")

public class MovieCollections {

    private Map<String, String> movieCollectionMap;

    public Map<String, String> getMovieCollectionMap() {
        return movieCollectionMap;
    }

    public void setMovieCollectionMap(Map<String, String> movieCollectionMap) {
        this.movieCollectionMap = movieCollectionMap;
    }

MovieCollectionsBean.java

@Configuration
public class MovieCollectionBean {

    @Bean
    public MovieCollections getMovieCollections() {
        return new MovieCollections();
    }

}

applications.properties

movies.M1001=SpiderMan
movies.M1002=Thor
movies.M1003=Logan
movies.M1004=Conjuring2
movies.M1005=StarWars

我收到一张空地图。为什么地图没有填充。

尝试将您的属性更新为 movies.names.M100... 并在 MovieCollections class

中将字段 movieCollectionMap 重命名为 names

当您使用 @ConfigurationProperties 时,字段名称应与 属性 匹配。所以在这种情况下,prefixmovies,字段名称是 names,hashmap 是具有代码和值的键,如电影名称

此外,您需要适当更新 gettersetter 方法。