简体   繁体   中英

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;   
    }
}

Is this any harm with this approach? I am trying to make change in the existing code where I am replacing the @Value with the getter as the method parameter. As I don't want to change the structure of the existing code I am trying to inject the method as bean as a replacement to @Value.

I suggest you to keep the @Value annotation instead of the whole @Bean configurations.

Why?

What if the getMethod() 's returned value needs to be changed very often? Everytime when you're changing something in the Product class, during build time it needs to be recompiled. What happens if the project is getting bigger and you're using this approach? It leads to longer build time and the more important thing is that this solution is not intuitive and it's hard to keep it clean. Don't think about complex solutions only to make the code look fancy . When you need to inject String values, the easiest approach is to create properties files (which won't get recompiled) and use the @Value annotation.

Now, if you want to add new methods without changing the structure of the existing code there are some patterns which you can apply like decorator pattern .

The main idea is simple: you're creating a decorator class which has an object of the type you need.

The easiest example (which you'll find everywhere on the internet) is the classic Shape example:

public interface Shape {
     String someMethod();
}
 
@Component
public class CustomShape implements Shape { //implement the method here }

And here is the decorator:

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";
   }
   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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