gpt4 book ai didi

java - Spring继承@Component并带有构造函数参数

转载 作者:行者123 更新时间:2023-12-02 11:38:10 32 4
gpt4 key购买 nike

我有一个服务需要在运行时创建代理。代理继承自代理基类。我想使用 spring 的 Autowired 功能,而不是自己进行依赖注入(inject)。

但是我遇到了这个问题,即使我将组件标记为scope=prototype,甚至@Lazy以防止在编译时发生任何事情。

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.my.project.AgentType1 required a bean of type 'com.my.project.POJO' that could not be found.

这是尝试创建代理的服务:

@Service
public class ProjectMain {
@Autowired
ApplicationContext context;

List<IAgent> agents = new ArrayList<>();

void SetupAgents(List<POJO> agentPojos) {
for(POJO agentPojo: agentPojos) {
IAgent agent = AgentFactory.CreateAgent(agentPojo, context);
agents.add(agent);
}
}
}

这是工厂类,未标记为 @Component 等。它使用传递给它的上下文来创建子类 bean。它尝试通过 getBean 方法传递构造函数参数。

public class AgentFactory {
public static IAgent CreateAgent(POJO agentPojo, ApplicationContext context) {
if (agentPojo.type.equals("AgentType1")) {
return context.getBean(AgentType1.class, agentPojo);
} else {
return context.getBean(AgentType2.class, agentPojo);
}
}
}

这是一个自定义注释,我发现继承场景需要它。

@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Component
@Inherited
@Lazy
@Scope("prototype")
public @interface AgentAnnotation {}

这些是基代理类和子代理类,它们需要名为 POJO 的自定义数据结构才能工作。

@AgentAnnotation
public class BaseAgent implements IAgent {

@Autowired
Environment env;

public BaseAgent(POJO agentPojo, String someotherdata) {

}

}

public class AgentType1 extends BaseAgent {

public AgentType1(POJO agentPojo) {
super(agentPojo, "mydata1");
...
}
}

public class AgentType2 extends BaseAgent {

public AgentType2(POJO agentPojo) {
super(agentPojo, "mydata2");
...
}
}

这是入门应用程序。

@ComponentScan(basePackages = "com.my.project", includeFilters = @ComponentScan.Filter(AgentAnnotation.class))
@EnableScheduling
@SpringBootApplication
public class MyApplication {

public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

我也尝试过配置方法:

@Configuration
public class BaseAgentConfig {
@Bean
@Scope("prototype")
public AgentType1 agentType1(POJO agentPojo) {
return new AgentType1(agentPojo);
}

@Bean
@Scope("prototype")
public AgentType2 agentType2(POJO agentPojo) {
return new AgentType2(agentPojo);
}
}

在本例中,我从 baseAgent 类中删除了 @AgentAnnotation,因为我们现在通过此配置进行实例化。还从主应用程序中删除了 ComponentScan 行。

这一次,@Autowired 不起作用。 baseAgent 类中的所有 Autowired 引用均为 null。

请提供解决此错误的最佳方法。谢谢。

最佳答案

找到问题和解决方案。

基本上,我期望子类继承 @Component 和 @Scope,但事实并非如此。

所以本质上,我需要用 @Component 和 @Scope("prototype") 注释每个子类。

另一个问题是我期待构造函数中的 Autowired 项,但现在还为时过早。添加 @PostConstruct 解决了这个问题。

因此,我最终删除了自定义注释和配置类,并进行了我刚才描述的更改。

关于java - Spring继承@Component并带有构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48776117/

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