gpt4 book ai didi

java - @Autowired 需要实例化参数的属性

转载 作者:行者123 更新时间:2023-11-30 02:16:50 25 4
gpt4 key购买 nike

我是 Spring Boot 新手,我需要知道如何在需要实例化参数的属性中使用 @autowired。请记住以下说明性情况。它会是这样的:

public class MyClassA{

public SpecificClass myMethod(){
//some logic
}

}

public class MyClassB extends MyClassA{

@Autowired
MyComponent myComponent (myMethod()); //here is my doubt, because my component needs a parameter to be built

}

@Component
public class MyComponent{
public MyComponent(SpecificClass foo){
this.foo=foo;
}

最佳答案

如果您的目的是使用依赖项注入(inject),那么这并不是真正正确的设计。不应该像这样直接依赖父类(super class)的方法。按照您应该做的那样间接注入(inject)依赖项将导致类似于以下内容的结果

public class MyClassB extends MyClassA {
@Autowired
private MyComponent myComponent;
}

@Configuration
public class SomeConfig {

@Bean
@Autowired
public MyComponent createComponent(SpecificClass foo) {
// SpecificClass is also injected, providing another layer of indirection
return new MyComponent(foo);
}
}

关于java - @Autowired 需要实例化参数的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48120820/

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