【发布时间】:2022-01-14 13:10:34
【问题描述】:
我的实体 bean 的 spring jar 创建为 export--java--JARfile,其中我的 bean 定义如下:
package com.my.beans;
@Component("expBean")
public class ExpBean {
}
我在这个 jar 中也有配置
package com.my;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class pBeanConfig {
@Bean
public ExpBean getExpBean() {
return new ExpBean();
}
}
我有客户端 spring 应用程序,我在上面添加只有 bean 作为外部依赖项的 jar,并在 spring 应用程序开始在客户端 spring 应用程序的主代码中使用以下代码时尝试获取我的 bean。
package com.my;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication()
@ComponentScan("com.my")
public class Application {
public static void main (String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
WMyBean bean = (WMyBean) ctx.getBean("expBean");
bean.doSomething();
}
}
但是当检查打印的 bean 定义列表时,我没有从外部 jar 中看到我的 bean,并且我得到以下错误。
"Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'expBean' available"
我尝试了很多选项,但不确定缺少什么。 选项 1
@ComponentScan("com.my")
@SpringBootApplication
public class Application {
选项 2
@ComponentScan({"com.my"})
@SpringBootApplication
public class Application {
在我错过的步骤上需要有价值的输入。
问题 1:我是否必须在客户端项目中进行配置更改才能访问我的依赖 jar 实体?
问题2:是否可以动态,在客户端项目配置中将所有没有配置的实体加载为@bean?
问题 3:每次我用更多实体更改我的依赖 jar 文件时,我是否需要构建客户端 jar?
谢谢
【问题讨论】:
-
如果 bean 在应用程序的子包中,则不需要
ComponentScan。getExpBean()将创建一个名为getExpBean的 bean,而Component("expBean")将创建一个名为expBean的 bean,对于单例实例来说,两者都是错误的,因为一个会覆盖另一个。 -
1.试试
ctx.getBean("getExpBean")(?) 2. 或者:@Impot(pBeanConfig.class)(and no (additional)@ComponentScan) 3. 或者试试@ComponentScan("com.my.beans")(留下名字expBean...) -
你能添加你的每个 jar 的 maven pom.xml 吗?
标签: java spring spring-boot