@Configuration
public class Product {
@Bean("xyz")
public String getMethod() {
return "abc";
}
}
@Component
public class Test {
String b;
Test(String xyz) {
this.b = xyz;
}
}
这种方法有害吗?我试图在现有代码中进行更改,在该代码中,我用getter作为方法参数替换@Value。由于我不想更改现有代码的结构,因此尝试将方法作为bean注入,以替换@Value。
答案 0 :(得分:0)
我建议您保留@Value
注释,而不要保留整个@Bean
的配置。
为什么?
如果getMethod()
的返回值需要经常更改怎么办?每次在Product
类中进行更改时,都需要在构建期间重新编译它。如果项目越来越大,而您正在使用这种方法,会发生什么?这会导致构建时间更长,更重要的是,此解决方案不直观,很难保持清洁。不要仅仅为了使代码看起来更精美而考虑复杂的解决方案。当需要注入String值时,最简单的方法是创建属性文件(不会重新编译)并使用@Value
批注。
现在,如果要添加新方法而不更改现有代码的结构,则可以应用某些模式,例如装饰器模式。
主要思想很简单:您正在创建一个 decorator 类,该类具有所需类型的对象。
最简单的示例(在互联网上随处可见)是经典的 Shape 示例:
public interface Shape {
String someMethod();
}
@Component
public class CustomShape implements Shape { //implement the method here }
这是装饰器:
public interface ShapeDecorator {
String someMethodExtended();
void someExtraMethod();
}
@Component
public class CustomShapeDecorator implements ShapeDecorator{
@Autowired
// @Qualifier - optional (only if you have more Shape implementations)
private Shape shape;
// now you can either:
// 1. provide new methods
@Override
public void someExtraMethod(){
System.out.println("Hello world!");
}
// 2. or you can EXTEND the Shape's "someMethod()" implementation
@Override
public String someMethodExtended(){
String oldString = this.shape.someMethod();
return oldString + " EXTENDED";
}
}