我是春天的新手,想知道为什么我的弹簧(不是弹簧靴(程序不起作用。这是一个简单的问题,这是最困扰我的地方。
我有一个主类如下:
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。我不确定我在这里错过了什么。 当我尝试在调试模式下运行应用程序时,我什至没有看到 ObjectMapper bean 创建方法命中的断点。我的理解是,它会在启动时启动弹簧 IOC,然后运行 main 方法。在我的情况下没有发生。
另外,我不知道它是否有效的另一件事是,当我创建此应用程序的jar并将其作为依赖项包含在另一个项目中时。基础项目可能没有 spring,甚至没有将 spring 用于该映射器。如果未在使用应用程序中设置 springIOC 容器,则包含此 jar 作为外部依赖项的项目如何能够在 secondClass 中调用 secondMethod。
有人可以帮我吗?
问题是你的 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"));
}
}
"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");
}
}
有时,我们正在定义的类的名称与已导入的某个包中已定义的另一个类匹配。在这种情况下,自动布线将不起作用。您已经创建了一个类 ObjectMapper,该类已在 jackson 库中定义。