问题
I have a requirement to set system property in spring boot application. I don't want to set it from command line.
My concern is what is the best practice to do it. Either from constructor Or inside main method. Below is sample for setting it from constructor
@SpringBootApplication
class Sample{
@Autowired
protected TempInfoDao tempInfoDao;
public Sample{
//Setting System property inside constructor
System.setProperty("vertx.hazelcast.config","./config/cluster.xml");
}
/**
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(Sample.class, args);
}
}
What is best approach ?
回答1:
Not good idea to set system variables from inside Java code. Basically, variables are meant to keep the code free from having any variable values.
Use properties files to store your configurations. Spring Boot does a great job externalising your configurations. It also let to you have environmental configurations in separate files and does a great job initialising it.
Refer to https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
回答2:
Setting System properties in constructor is not a good approach.
You could use a separate class and spring annotations to do that like below.
@Profile("production")
@Component
public class ProductionPropertySetter {
@PostConstruct
public void setProperty() {
System.setProperty("http.maxConnections", 15);
}
}
回答3:
You should base your Sample class on a special class, written by you. I propose the name BaseSettingProperties
public class TestBaseWithProperties extends AbstractTestNGSpringContextTests {
{
System.setProperty("name.of.property", "value/of/property");
}
}
This way you can guarantee that properties would be set really before all reading the context and wiring. And you can surely use these properties even in include
d XMLs.
It is possible to set variables in beans, by putting properties in some file.of.needed.properties and using it
<bean id="prop" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="file.of.needed.properties" />
</bean>
, but you cannot guarantee the order of property setting and include
calling. Because it is not calling but physical including. And you cannot set dependency of include
on the properties setting bean - I found no syntax for that :-(. On the other hand, yes, I use the very old Spring of 3rd version, but I couldn't find a solution in the recent internet.
来源:https://stackoverflow.com/questions/51867161/how-to-set-system-property-in-spring-boot-application