gpt4 book ai didi

java - 来自不同 Maven 模块的 Autowire 类?

转载 作者:行者123 更新时间:2023-11-30 04:37:28 28 4
gpt4 key购买 nike

我有一个具有以下结构的 Maven 项目:

spring-di-test
+--spring-di-test-core
| com.example.core.DITestMain
+--spring-di-test-store
com.example.store.DITest
com.example.store.RandomStringService

其中 spring-di-test 是根项目,下面的两个是模块。

我的类(class)如下所示:

DITestMain 位于 spring-di-test-core

public class DITestMain {
public static void main(String[] args) {
new DITest().run();
}
}

applicationContext.xml 位于 spring-di-test-core 的资源文件夹

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:spring-configured/>
<context:component-scan base-package="com.example.*" annotation-config="true"/>

</beans>

DITest 位于 spring-di-test-store

@Configurable(preConstruction = true)
@Controller
public class DITest {
@Autowired(required=true)
private RandomStringService randomStringService;

public void run() {
System.out.println(randomStringService.getRandomString());
}
}

RandomStringService 位于 spring-di-test-store

@Service("randomStringService")
public class RandomStringService {

private final Random random;

public RandomStringService() {
random = new Random();
}

public String getRandomString() {
StringBuilder sb = new StringBuilder();
int length = random.nextInt(20);
for (int i = 0; i < length + 1; i++) {
sb.append(new Character((char) ('a' + random.nextInt(20))));
}
return sb.toString();
}
}

applicationContext.xml 位于 spring-di-test-store

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:spring-configured/>
<context:component-scan base-package="com.example.*" annotation-config="true"/>

</beans>

当我运行 DITestMain 时,我收到 randomStringService 的 NullPointerException。出了什么问题?

最佳答案

1:您没有在 main 方法中创建 Spring 上下文

2:您是否完成了启用加载时编织所需的所有配置(以便您的 @Configurable bean 能够工作)?

看看http://static.springsource.org/spring/docs/3.0.x/reference/aop.html#aop-using-aspectj并仔细阅读整章。

关于java - 来自不同 Maven 模块的 Autowire 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13136433/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com