有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java组件扫描和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");
    }
}

第二类定义如下:

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。我不确定我错过了什么。 当我尝试在调试模式下运行应用程序时,我甚至没有看到ObjectMapperbean创建方法中出现断点。我的理解是,它会在启动时启动spring IOC,然后运行main方法。我的情况不是这样

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

谁能帮帮我吗


共 (3) 个答案

  1. # 1 楼答案

    有时,我们定义的类的名称和我们导入的某个包中已经定义的另一个类相匹配。在这种情况下,自动布线不起作用。您已经创建了一个已经在jackson库中定义的类ObjectMapper

  2. # 2 楼答案

    “SecondClass.secondMethod”是一个静态方法。此静态方法的执行不会在Spring应用程序上下文下运行

    您需要加载Spring应用程序上下文,以便触发“@PostConstruct”并分配“objectMapper”

    以下是示例代码:

    @Configuration
    @ComponentScan("com.something")
    public class Main {
        public static void main(String[] args) throws IOException {
            ApplicationContext context = new AnnotationConfigApplicationContext(Main.class);
            SecondClass.secondMethod("someString");
    
        }
    }
    
  3. # 3 楼答案

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

    将主类更改为以下内容:

    @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"));
        }
    }