繁体   English   中英

在 spring 中使用 String 作为 bean 的返回类型是否安全?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM