首页 > 解决方案 > ComponentScan 和 bean 的自动装配似乎在 Spring 应用程序中不起作用

问题描述

我是春天的新手,想知道为什么我的 spring(不是 springboot)程序不起作用。这是一个简单的,这是最困扰我的。

我有一个主要课程如下:

package com.something.main;

@Configuration
@ComponentScan (
        "com.something"
)
public class Main {
    public static void main(String[] args) throws IOException {
       String someValue = SecondClass.secondMethod("someString");
    }
}

SecondClass 定义如下:

package com.something.somethingElse;

@Component
public class SecondClass {
   @Autowired
   private ObjectMapper om;

    private static ObjectMapper objectMapper;

    @PostConstruct
    public void init(){
       objectMapper = this.om;
    }

    public static String secondMethod(String input){
      String x = objectMapper.<<someOperation>>;
      return x;
    }
}

ObjectMapper 在 spring ioc 中注入如下:

package com.something.config;
@Configuration
public class ObjectMapperConfig {
    @Bean
    ObjectMapper getObjectMapper(){
        ObjectMapper om = new ObjectMapper();
        return om;
    }
}

现在,当我尝试在 dubug 模式下运行 main 方法时, secondMethod 始终将 objectMapper 设为 null。我不确定我在这里缺少什么。当我尝试在调试模式下运行应用程序时,我什至看不到 ObjectMapper bean 创建方法中的断点。我的理解是它会在启动时支持 spring IOC,然后运行 ​​main 方法。在我的情况下没有发生。

另外,我不知道它起作用的另一件事是,当我创建此应用程序的 jar 并将其作为依赖项包含在另一个项目中时。基础项目可能没有弹簧,甚至没有为该映射器使用弹簧。如果 springIOC 容器未在消费应用程序中设置,那么包含此 jar 作为外部依赖项的项目如何能够在 secondClass 中调用 secondMethod。

有人可以帮帮我吗?

标签: javaspring

解决方案


问题是你的 Spring 上下文没有在这里初始化,因此 SecondClass 不是一个 bean,因此@PostConstuct不会被调用,这会导致objectMapper对象没有被初始化,因此你可能会得到 nullpointer 异常。您需要初始化弹簧上下文。

将您的 Main 类更改为以下内容:

@Configuration
@ComponentScan (
        "com.something"
)
public class Main {
    public static void main(String[] args) throws IOException {

        // Initialise spring context here, which was missing
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Main.class);

 //      SecondClass cls = context.getBean(SecondClass.class);
  //     System.out.println(cls.secondMethod("something"));
       System.out.println(SecondClass.secondMethod("someString"));
    }
}

推荐阅读