spring boot autowired空指针异常

时间:2017-06-18 15:56:58

标签: java spring-boot nullpointerexception autowired

我正在使用spring boot和java configs,但@autowired似乎不起作用。 我得到了一个N​​PE,我已经检查了其他问题,但我无法看到这种行为的原因。以下是我的代码: -

    package com.bhargo;
    //skipping imports
    @SpringBootApplication
    public class Main implements CommandLineRunner {

        @Autowired
        private BuilderFactory builderFactory;

        @Autowired
        private LinksBuilder linksBuilder;

        private final static File fileDir = new File("D:\\ml-20m");
        public static void main(String[] args) {
            SpringApplication.run(Main.class, args);
        }

        @Override
        public void run(String... args) throws Exception {
            Main main = new Main();
            main.getFiles();
        }

        private void getFiles () {
            Builder[] builder = new Builder[1];
            Arrays.stream(fileDir.listFiles()).filter(n -> !n.getName().contains("txt") /*&& n.getName().contains("links")*/)
                    .forEach(f ->{
                        //builder factory is NULL 
                        builder[0] = builderFactory.getBuilderFor(f.getName());
    ....
    ....
@Bean
    public BuilderFactory builderFactory() {
        BuilderFactory builderFactory = new BuilderFactory();
        Map<String, Builder> map = new HashMap<>();
        map.put("genome-scores.csv",genomeScoreBuilder());
        map.put("genome-Tags.csv",genomeTagBuilder());
        map.put("links.csv", linksBuilder());
        map.put("movies.csv", movieBuilder());
        map.put("ratings", ratingBuilder());
        map.put("tags.csv", tagBuilder());
        builderFactory.setBuilderMap(map);
        return builderFactory;
    }

BuilderFactory类: -

package com.bhargo.model.builder;

import com.bhargo.Builder;

import java.util.Map;

public class BuilderFactory {

    private Map<String, Builder> builderMap;

    public BuilderFactory() {
    }

    public Map<String, Builder> getBuilderMap() {
        return builderMap;
    }

    public void setBuilderMap(Map<String, Builder> builderMap) {
        this.builderMap = builderMap;
    }

    public Builder getBuilderFor(String fileName) {
        return builderMap.get(fileName);
    }
}

1 个答案:

答案 0 :(得分:4)

当您自己创建一个类的实例时,如下一行

Main main = new Main();

Spring不了解实例,自动装配不起作用。 在你的情况下,只有行

this.getFiles();
运行方法中的

应该足够了。