[英]ComponentScan and autowiring of beans don't seem to work in a spring application
我是春天的新手,想知道为什么我的 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;
}
}
在spring ioc中注入ObjectMapper如下:
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 。
有人可以帮帮我吗?
问题是你的 Spring 上下文没有在这里初始化,因此 SecondClass 不是一个 bean,因此@PostConstuct
不会被调用,这导致objectMapper
对象没有被初始化,因此你可能会得到空指针异常。 您需要初始化 spring 上下文。
将您的 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"));
}
}
“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");
}
}
有时,我们定义的类的名称与我们导入的某个包中已经定义的另一个类相匹配。 在这种情况下,自动装配将不起作用。 您已经创建了一个已经在 jackson 库中定义的类 ObjectMapper。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.