[英]Is it safe to use String as a return type of a bean in spring?
@Configuration
public class Product {
@Bean("xyz")
public String getMethod() {
return "abc";
}
}
@Component
public class Test {
String b;
Test(String xyz) {
this.b = xyz;
}
}
這種方法有什么害處嗎? 我正在嘗試對現有代碼進行更改,在該代碼中,我將 @Value 替換為 getter 作為方法參數。 由於我不想更改現有代碼的結構,因此我嘗試將該方法作為 bean 注入以替代 @Value。
我建議您保留@Value
注釋而不是整個@Bean
配置。
為什么?
如果getMethod()
的返回值需要經常更改怎么辦? 每當您更改Product
class 中的某些內容時,在構建期間都需要重新編譯它。 如果項目變得越來越大並且您正在使用這種方法會發生什么? 它會導致更長的構建時間,更重要的是這個解決方案不直觀,而且很難保持干凈。 不要僅僅為了使代碼看起來花哨而考慮復雜的解決方案。 當您需要注入 String 值時,最簡單的方法是創建屬性文件(不會重新編譯)並使用@Value
注釋。
現在,如果你想在不改變現有代碼結構的情況下添加新方法,那么你可以應用一些模式,比如裝飾器模式。
主要思想很簡單:您正在創建一個裝飾器class ,它具有您需要的類型的 object 。
最簡單的示例(您可以在 Internet 上隨處找到)是經典的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";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.