Spring XML + properties configuration to Java Class - java

I have the following configuration piece on my xml file:
<util:properties id="apiConfigurator" location="classpath:api.properties" scope="singleton"/>
And here is my properties file:
appKey=abc
appSecret=def
On my spring classes I get some of the values like this:
#Value("#{apiConfigurator['appKey']}")
I would like to create a #Configuration class in Spring to parse the properties file in a way that
#Value("#{apiConfigurator['appKey']}")
still works thorough my classes that use this. How do I properly do that?

When you specify
<util:properties .../>
Spring registers a PropertiesFactoryBean bean with the name/id that you also specified.
All you need to do is to provide such a #Bean yourself
// it's singleton by default
#Bean(name = "apiConfigurator") // this is the bean id
public PropertiesFactoryBean factoryBean() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("api.properties"));
return bean;
}

Related

Binding spring boot application properties to java.util.properties

I am creating a spring-boot application which also creates bean for one of the classes of an external lib, this external java bean needs java.util.properties as one of the constructor parameter. Although I can use configurationPropeties with prefix to read properties from the spring boot loaded property file and convert it to java.util.properties.However, I don't want any additional prefix in the property file. is there any other way where I can convert the spring-boot loaded env or property source to java.util.properties
here is the code for reference
#Configuration
public class AppConfig {
#ConfigurationProperties(prefix = "some.prefix")
#Bean
public Properties getProperties() {
return new Properties();
}
#Bean
public ExternalClass externalClass() throws ConfigException {
return ExternalClass.getInstance(getProperties());
}
}
the above code work nicely, but I need to add an unnecessary prefix to the properties for conversion. could someone suggest any other approach apart from adding prefix to the propeties
Take a look at this documentation. It explains property binding techniques used in spring-boot.

Removing PropertySourcesPlaceHolderConfigurer bean Autowiring doesn't work

What is the purpose of adding "PropertySourcesPlaceholderConfigurer" as a bean in spring? . As far as I researched it says when you name your property file as application.properties, spring will automatically take the file when it is in src/main/resources Folder. Having so, when I remove the Bean Declaration for PropertySourcesPlaceholderConfigurer, it says couldn't autowire the property.
What am I missing, Why isn't it working without PropertySourcesPlaceholderConfigurer
Sample 1:
#Configuration
#PropertySource(value = { "application.properties" }, ignoreResourceNotFound = true)
#ComponentScan(basePackages = { Some Package })
public class ApplicationConfig {
ApplicationConfig() {
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
Sample 1 works fine, When I remove #PropertySources and #PropertySourcesPlaceholderConfigurer bean since spring will pick up application.properties automatically, it doesn't work.
it says when you name your property file as application.properties,
spring will automatically take the file when it is in
src/main/resources Folder
As I know - this is correct only for Spring Boot.
For spring core you should define you prps in contxet.
There are several ways.
In xml
< context:property-placeholder location="classpath:application.properties" />
or using Java annotation
#Configuration
#PropertySource("classpath:application.properties")
It's not necessary to define PropertySourcesPlaceholderConfigurer since Spring 4.3RC2

Properties not found with Spring PropertySource

Config
#Configuration
#PropertySources({
#PropertySource("classpath*:properties/test-database.properties")
})
public class DataSourceConfiguration {//...
}
Prop location
D:\Projects\opti\dao\src\main\resources\properties\test-database.properties
D:\Projects\opti\dao\src\main\resources marked as resource folder.
To avoid this kind of problem the issue is to set the jboss.server.config.dir in VM arguments like that :
-Djboss.server.config.dir="[jboss_repository]/server/[default-all-standard-standalone]/conf" –server
and u set PropertySource like this :
#Configuration
#PropertySource("file:${jboss.server.config.dir}/file.properties")
Or you set ur property like that
#PropertySource(value = "classpath:application.properties")
When executed, properties will be imported from the application.properties file, located in the classpath root.
It isn't clear well the your problem considering the details of your question, but a typical problem whit #PropertySource is that yuo have configure a spring bean for manage the properties. In old years in which xml was the best way for configure Spring you used a namespace configuration that configure a spring bean for use proeprties in your bean, mainly with #Value. In java config for benefit of same behaviour you have configure a bean like belove:
#Bean
public static PlaceholderConfigurerSupport propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
I hope that this can help you

Where do I put my XML beans in a Spring Boot application?

I'm getting back into Spring (currently v4). It's all wonderful now with #SpringBootApplication and the other annotations but all the documentation seems to forget to mention how I define other beans in XML!
For example I'd like to create an "SFTP Session Factory" as defined at:
http://docs.spring.io/spring-integration/reference/html/sftp.html
There is a nice bit of XML to define the bean but where on earth do I put it and how do I link it in? Previously I did a:
ApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:applicationContext.xml");
to specify the file name and location but now that I'm trying to use:
ApplicationContext ctx = SpringApplication.run(Application.class);
Where do I put the XML file? Is there a magic spring name to call it?
As long as you're starting with a base #Configuration class to begin with, which it maybe sounds like you are with #SpringBootApplication, you can use the #ImportResource annotation to include an XML configuration file as well.
#SpringBootApplication
#ImportResource("classpath:spring-sftp-config.xml")
public class SpringConfiguration {
//
}
You also can translate the XML config to a Java config. In your case it would look like:
#Bean
public DefaultSftpSessionFactory sftpSessionFactory() {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory();
factory.setHost("localhost");
factory.setPrivateKey(new ClassPathResource("classpath:META-INF/keys/sftpTest"));
factory.setPrivateKeyPassphrase("springIntegration");
factory.setPort(22);
factory.setUser("kermit");
return factory;
}
You can put this method in the class with the #SpringBootApplication annotation.
Spring boot ideal concept is avoid xml file. but if you want to keep xml bean, you can just add #ImportResource("classPath:beanFileName.xml").
I would recommend remove the spring-sftp-config.xml file. And, convert this file to spring annotation based bean. So, whatever class has been created as bean. Just write #Service or #Component annotation before class name. for example:
XML based:
<bean ID="id name" class="com.example.Employee">
Annotation:
#Service or #Component
class Employee{
}
And, add #ComponentScan("Give the package name"). This is the best approach.

How to use spring configuration class in a controller function

I have searched multiple pages thru google. It tells you how to load the configuration thru the annotation. But the tutorial always forget how to use the created object in the controller.
Here is my code.
Properties file (demo.properties)
demo.out_path=c:\demo_dir
Demo Config file (DemoAppConfig.java)
#Configuration
#PropertySource("classpath:demo.properties")
public class DemoAppConfig {
#Value("${demo.out_path}")
private String OutPath;
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
Servlet config (demo-servlet.xml)
<!-- Properties -->
<context:property-placeholder location="classpath:demo.properties" ignore-unresolvable="true" />
How do I call the properties inside a controller? I tried auto wire annotation of DemoAppConfig as a property but it fails. I tried instantiating the DemoAppConfig as a new class but all property were not loaded.
Note: Used spring version 4.1.7.RELEASE
I know one way is to configure system property look up in xml config as below:
<util:properties id="systemPropertyLookup" location="classpath:demo.properties"/>
Of course, you need to add in spring-util schema declaration:
<beans ....
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="....
http://www.springframework.org/schema/util/spring-util.xsd">
Then inject your property value into your controller as follow:
#Value("#{systemPropertyLookup['demo.out_path']")
private String OutPath;
Checking my project, this is how I have been loading persistence.properties and I have been able to use #Value just like you have configured:
#Configuration
#ComponentScan(basePackageClasses = Application.class)
class ApplicationConfig {
#Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();
ppc.setLocation(new ClassPathResource("/persistence.properties"));
return ppc;
}
}
Make sure that it is on the classpath and that the compiler copies the resource file into the distributable.

Categories

Resources