Following chapter 5 of Spring in action fifth edition I have tried to establish my own confuguration variables with spring boot:
#Component
#ConfigurationProperties(prefix = "myprops")
public class MyClass {
private int myvar1;
// Getters and setters...
}
Written in file application.properties only this:
myprops.myvar1=3333
MyClass.getMyvar1() should return 3333 now but it still returns the default int value: 0.
#SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
#Bean
public CommandLineRunner foo(ApplicationContext ctx) {
return args -> {
MyClass mc = new MyClass();
int x = mc.getMyvar1();
System.out.println(x);
};
}
}
Add #EnableConfigurationProperties(MyClass.class) to Demo1Application
If we don’t use #Configuration in the POJO, then we need to add #EnableConfigurationProperties(ConfigProperties.class) in the main Spring application class to bind the properties into the POJO:
Related
I want to new a project like mybatis-spring-boot-starter, I use springboot 2.3.2, but something wrong.
First of all, I define a BatisProperties.java like following:
#ConfigurationProperties(prefix = BatisProperties.MYBATIS_PREFIX)
public class BatisProperties {
public static final String MYBATIS_PREFIX = "batis";
private String MyClassName;
...
}
then, a BatisAutoConfiguration.java
#Configuration
#ConditionalOnClass({ SqlSessionFactory.class, SqlSessionFactoryBean.class })
#EnableConfigurationProperties(BatisProperties.class)
public class BatisAutoConfiguration implements InitializingBean {
private final BatisProperties properties;
#Override
public void afterPropertiesSet() throws Exception {
checkConfigFileExists();
}
private void checkConfigFileExists() {
System.out.println(this.properties.getMyClassName());//null here
if (this.properties.isCheckConfigLocation() && //code from mybatis-spring-booot-starter
StringUtils.hasText(this.properties.getConfigLocation())) {
Resource resource = this.resourceLoader.getResource(this.properties.getConfigLocation());
Assert.state(resource.exists(),
"Cannot find config location: " + resource + " (please add config file or check your Mybatis configuration)");
}
}
And in /resource/META_INF/spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
xxx.BatisAutoConfiguration
above are all in a starter, I compile it to a jar file and use this jar file in another project(project TWO), in project TWO, I define .properties or .yml in /resource directory, contents are:
batis.my-class-name=xxxx.xxxx
Finally, a DemoApplication.java or Test.java like following:
DemoApplication.java
#SpringBootApplication
public class DemoApplication {
#Autowired
private BatisProperties properties;
private static BatisProperties batisProperties;
#PostConstruct
public void init() {
batisProperties = properties;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println(batisProperties.toString());//xxxx.BatisProperties#436390f4
System.out.println(batisProperties.getMyClassName());//null
}
}
Test.java
#SpringBootTest
class Test {
#Autowired
private BatisProperties properties;
#Test
void contextLoads() {
System.out.println(properties);// some bean in Spring IOC
System.out.println(properties.getDatasourceConfigProviderClassName());// null
}
}
Above comments are the results: We can find BatisProperties Bean in Spring IOC, but all properties are null.
So anybody can help? I don't know whether it is caused by the version of SpringBoot
I would improve the BatisProperties class to be as:
#Configuration
#ConfigurationProperties(prefix = "batis")
public class BatisProperties {
private String MyClassName;
...
// Make sure you have getters and setter for properties!
// If you use Lombok, put #Data on this class.
...
}
There is no need to explicitly have BatisAutoConfiguration.java. Just let Spring initialize it for you. Completely remove the class BatisAutoConfiguration.java. Also do not use static fields for the property class.
Try the following:
#SpringBootApplication
#EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Or also more explicit, but not needed:
#SpringBootApplication
#ComponentScan(basePackages = {"my.app.org"}) // prefix, where BatisProperties is
#EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
or:
#SpringBootApplication
#EnableAutoConfiguration
#Import(BatisProperties.class)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
The BatisProperties should be available anywhere in your App.
I just created a really basic spring boot application using spring initializer and am trying things out. I want to load a list from a yaml configuration file, but it always returns empty.
I have a custom configuration class
#ConfigurationProperties("example-unit")
#EnableConfigurationProperties
public class ConfigurationUnit {
public List<String> confiList = new ArrayList<>();
public List<String> getConfiList() {
return this.confiList;
}
}
And my main class looks like this
#SpringBootApplication
public class DemoApplication {
static ConfigurationUnit configurationUnit = new ConfigurationUnit();
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
List<String> hello = configurationUnit.getConfiList();
System.out.print("");
}
}
I have put the application.yaml into resources folder.
example-unit:
- string1
- string2
- hello22
I searched here and online, but can't figure out what's the issue and nothing I changed helped. I know I must be doing something wrong.
This statement is wrong static ConfigurationUnit configurationUnit = new ConfigurationUnit();
you should not create the object
Spring only injects the properties into the beans that are handled by application context, and spring creates beans of classes that are annotated with # Configuration
ConfigurationUnit
#Configuration
#ConfigurationProperties("example-unit")
public class ConfigurationUnit {
public List<String> confiList;
public List<String> getConfiList() {
return this.confiList;
}
}
DemoApplication In the spring boot main get the bean from applicationcontext and from it get the list object
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(DemoApplication.class, args);
ConfigurationUnit unit = context.getBean("configurationUnit"):
System.out.print(unit. getConfiList());
}
}
Put your list under prefix.property. In your case example-unit.confi-list:. Usually provide a setter for your property: setConfiList(List<String> strings). But since you already initialized it as empty Array list this setter is obsolete says this. There is also advice to add Enable-annotation to Application class:
Application class should have #EnableConfigurationProperties annotation
Here is the reference on how Spring Bboot Configurtion Binding works.
Specifically for your question, this is an example of app that achives your goal:
application.yml
example-unit:
confiList:
- string1
- string2
- hello22
sources
#SpringBootApplication
#EnableConfigurationProperties(ConfigurationUnit.class)
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
ConfigurationUnit configurationUnit = context.getBean(ConfigurationUnit.class);
System.out.println(configurationUnit.getConfiList());
}
}
#ConfigurationProperties("example-unit")
public class ConfigurationUnit {
public List<String> confiList = new ArrayList<>();
public List<String> getConfiList() {
return this.confiList;
}
}
Here is an example :
Application.yml:
example-unit: string1,string2,hello22
ConfigurationUnit.class:
#Component
#PropertySource(value="classpath:application.yml")
public class ConfigurationUnit {
#Value("#{'${example-unit}'.split(',')}")
private List<String> confiList;
public List<String> getConfiList() {
return confiList;
}
}
DemoFileLoadApplication.class:
#SpringBootApplication
public class DemoFileLoadApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DemoFileLoadApplication.class, args);
ConfigurationUnit configurationUnit = context.getBean(ConfigurationUnit.class);
System.out.println(configurationUnit.getConfiList());
}
}
Output:
[string1, string2, hello22]
I have been trying to get a very basic example of a custom PropertySource running in a Spring Application.
This is my PropertySource:
public class RemotePropertySource extends PropertySource{
public RemotePropertySource(String name, Object source) {
super(name, source);
}
public RemotePropertySource(String name) {
super(name);
}
public Object getProperty(String s) {
return "foo"+s;
}
}
It gets added to the ApplicationContext via an ApplicationContextInitializer:
public class RemotePropertyApplicationContextInitializer implements ApplicationContextInitializer<GenericApplicationContext> {
public void initialize(GenericApplicationContext ctx) {
RemotePropertySource remotePropertySource = new RemotePropertySource("remote");
ctx.getEnvironment().getPropertySources().addFirst(remotePropertySource);
System.out.println("Initializer registered PropertySource");
}
}
Now I created a simple Unit-Test to see if the PropertySource is used correctly:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = RemotePropertySourceTest.ContextConfig.class, initializers = RemotePropertyApplicationContextInitializer.class)
public class RemotePropertySourceTest {
#Autowired
private UnderTest underTest;
#Autowired
Environment env;
#Test
public void testContext() {
assertEquals(env.getProperty("bar"),"foobar");
assertEquals(underTest.getFoo(),"footest");
}
#Component
protected static class UnderTest {
private String foo;
#Autowired
public void setFoo(#Value("test")String value){
foo=value;
}
public String getFoo(){
return foo;
}
}
#Configuration
#ComponentScan(basePackages = {"test.property"})
protected static class ContextConfig {
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
return configurer;
}
}
}
Accessing the value via the Environment gives me the correct result ("foobar"), but using the #Value-Annotation fails. As far as I have read in the documentation the PropertySourcesPlaceholderConfigurer in my Configuration should automatically pick up my PropertySource from the environment but apparently it does not. Is there something I am missing?
I know that accessing properties explicitly via the environment is preferrable but the existing application uses #Value-Annotations a lot.
Any help is greatly appreciated. Thanks!
To get value from property source with #Value you have to use ${} syntax:
#Autowired
public void setFoo(#Value("${test}")String value){
foo=value;
}
Take a look at official documentation.
I'm trying to get some properties from the command line when I start my app. I really try a lot of solution but nothings is working. I'll only use #Value as a last solution
java -jar myjar.jar --test.property=something
Here's some classes
Main class
#SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(TestApplication.class);
builder.run(args);
}
}
Config class
#Configuration
#EnableConfigurationProperties(StringProperties.class)
public class StringConfiguration {
#Autowired
private StringProperties stringProperties;
#Bean(name = "customBeanName")
public List<String> properties() {
List<String> properties = new ArrayList<>();
properties.add(stringProperties.getString());
return properties;
}
}
Properties class
#Component
#ConfigurationProperties("test")
public class StringProperties {
private String property;
public String getString() {
return property;
}
}
Ops.....I have tested your code.It is setProperty that missed in StringProperties.
public void setProperty(String property) {
this.property = property;
}
i create simple spring project and i need to use annotation #Autowired but when i run project, i get exception NullPointerException.
This is my classes:
Main.java
public class Main {
#Autowired
private static InjectClass injectClass;
public static void setInjectClass(InjectClass injectClass) {
Main.injectClass = injectClass;
}
public static void main(String[] args) {
injectClass.hello(); //NullPointerException
}
}
ConfigurationBean
#Configuration
public class ConfigurationBean {
#Bean
public InjectClass injectClass(){
return new InjectClass();
}
}
InjectClass
public class InjectClass {
public void hello(){
System.out.println("Autowired success!");
}
}
You need to initiate application contex before using any bean.
You can do it by writing following code in starting of your main method.
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
ConfigurationBean.class);