BadPractice10 - SpotBugsExtensionForSpringFrameWork/CS5098 GitHub Wiki
Bug name: Try not hard code the value in @Value, since it causes a recompile process to change the value.
Reading your data from a file have the following benefits Link :
- You don't have to wait for the program to recompile for every change in the data. For a fairly large program, this can take time.
- Your users can change the data without even having access to the source.
- You can have different data sets between which you can switch just by changing the config file name.
- "However, hard-coding the value in the code is not a good idea; to change it, we would need to recompile the program. Even if you choose annotation-style DI, a good practice is to externalize those values for injection. To externalize the message, let’s define the message as a Spring bean in the annotation configuration file, as shown in the following code snippet:" (Pro Spring - chapter 3 (60 page))
import com.apress.prospring5.ch2.decoupled.MessageProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("provider")
public class ConfigurableMessageProvider implements MessageProvider {
private String message;
@Autowired
public ConfigurableMessageProvider(
(@Value("Configurable message") String message) { // Do not hard code like this, since it cause recompile process.
this.message = message;
}
@Override
public String getMessage() {
return this.message;
}
}
Use SpEL
@Value("#{injectSimpleConfig.name}")
<beans ...>
<context:component-scan
base-package="com.apress.prospring5.ch3.annotated"/>
<bean id="message" class="java.lang.String"
c:_0="I hope that someone gets my message in a bottle"/>
</beans>
- "Using Injection Parameters" in Pro Spring 5 (66 page)
- "Injecting Simple Values"
- "Injecting Values by Using SpEL"
- https://stackoverflow.com/questions/17859199/hardcoding-values-vs-reading-from-file
- https://www.baeldung.com/spring-value-annotation
- https://www.baeldung.com/spring-value-defaults