Am new to spring, had defined the ApplicaionConfig.java there I placed the property file details.
package com.rao.first;
//
// import statements
//
#Configuration
#ComponentScan(basePackageClasses = { ApplicationConfig.class }, basePackages = { "com.rao.first" })
#PropertySources({
#PropertySource("file:${webapp.root}/resources/config/application.properties"),
#PropertySource(value = "file:${conf.dir}/someother.properties", ignoreResourceNotFound = true) })
class ApplicationConfig
{
#Bean
ServletContextListener logbackConfigListener()
{
return new LogbackConfigListener();
}
}
and defined some controller classes.
package com.rao.first.controller;
//
// import statements
//
#Controller
#RequestMapping(value = "/first")
public class FirstController
{
private String viewerUrl;
#Inject
public FirstController(Environment env)
{
this.viewerUrl = env.getProperty("property1");
}
//
//
}
But here first controller is executing, after that ApplicaitonConfig is executing, so unable to get the data from property file.
And spring-servlet.xml file configurations are
<context:component-scan base-package="com.rao.first.view" />
<context:component-scan base-package="com.rao.controller.security" />
<context:component-scan base-package="com.rao.controller" />
Please guide me how can set order of execution?
You could use org.springframework.context.annotation.PropertySource annotation to retrieve values from a properties file.
So your controller class could be like following:
package com.rao.first.controller;
import org.springframework.context.annotation.PropertySource;
//
// import statements
//
#Controller
#RequestMapping(value = "/first")
#PropertySource("classpath:/com/rao/app.properties")
public class FirstController
{
private String viewerUrl;
#Autowired
Environment env;
public FirstController()
{
this.viewerUrl = env.getProperty("property1");
}
//
//
}
I hope it helps you, bye.
Related
I would like to add the source of database.properties which is in ProjectName/src/database.properties to AppConfig.class which is in ProjectName/src/device/spring/configaccording to https://www.journaldev.com/17053/spring-jdbctemplate-example
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import tekranchecklist.model.*;
#Configuration
#ComponentScan("device.spring.dao","device.model","device.spring.config","device.Main")
public class AppConfig {
#Autowired
Environment environment;
private final String URL = "URL";
private final String USER = "root";
private final String DRIVER = "DRIVER";
private final String PASSWORD = "PASSWORD";
#Bean
DataSource dataSource() {
DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
driverManagerDataSource.setUrl(environment.getProperty(URL));
driverManagerDataSource.setUsername(environment.getProperty(USER));
driverManagerDataSource.setPassword(environment.getProperty(PASSWORD));
driverManagerDataSource.setDriverClassName(environment.getProperty(DRIVER));
return driverManagerDataSource;
}
}
I tried to use #PropertySource("classpath:database.properties") but it is syntax error that: class, interface or enum expected. Can someone help me how I should add my .properties file path with #PropertySource?
#PropertySource is an annotation that can be used only on types, that is interface, class, enum :
#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
#Documented
#Repeatable(PropertySources.class)
public #interface PropertySource {...}
This class, interface or enum expected message is a compilation error that means that you specified the annotation on a target that doesn't match to a type.
So move it at the correct place :
#PropertySource("classpath:database.properties")
public class AppConfig {
....
}
You can use #PropertySource with either #Value or Environment as shown below.
Assuming this is your application property file.
app.value.example=v1
app.environment.example=e1
Using #PropertySource with #Value
#Configuration
#PropertySource("classpath:application.properties")
public class ApplicationContig {
#Value("${app.value.example:defaultValueCanBeHere}")
private String propertyValue;
public void usePropertyValue() {
// You can use it here
}
}
Using #PropertySource with Environment
#Configuration
#PropertySource("classpath:application.properties")
public class ApplicationContig {
#Autowired
private Environment environmentValue;
private void useEnvironmentValue() {
String value = environmentValue.getProperty("app.environment.example");
// You can then use it here.
}
}
With Spring >= 4
#Configuration
#PropertySources({
#PropertySource(value = "classpath:application.properties"),
#PropertySource(value = "classpath:another.properties"),
#PropertySource(value = "classpath:missing-file.properties",
ignoreResourceNotFound = true)})
public class ApplicationContig {
// You can either use #Value or Environment as demonstrated above
}
I hope this will help.
I am new to Spring MVC and I would like your help on how to read a property file in a WebAppConfig.java using a Map and with #Bean and #AutoWire. The constants in the property file is used as a common strings in different files (like an enum).
myproperty.properties
user.first_name = Jane
user.age = 23
WebAppConfig.java
#Configuration
#ComponentScan( {"com.nokia.care.triggerengine", "com.nokia.care.gui.commons"} )
#EnableWebMvc
#EnableTransactionManagement
#PropertySource( "classpath:application.properties" )
public class WebAppConfig
extends WebMvcConfigurerAdapter
{
...
Furthermore the webappconfig.java already has an existing #propertsource.
Thank you for your help.
With spring-boot you may create a separate config component and then autowire it.
#Component
#ConfigurationProperties(prefix = "user")
public class UserConfig {
private String userFirstName;
private String userAge;
//getters and setters
}
public class WebAppConfig extends WebMvcConfigurerAdapter {
#Autowired
private UserConfig userConfig;
...
}
Without spring-boot you should find needed dependencies for using #ConfigurationProperties
Use this #Value to access value in bean and repository class
#Value("${user.first_name}")
private String userFirstName;
#Value("${user.age}")
private String userAge;
A good way to do this is read all the configuration in an AppConfig class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
#Configuration
#PropertySource("classpath:myproperty.properties")
public class AppConfig {
#Autowired
private Environment env;
public Environment getEnv(){
return env;
}
}
This way the env variable will have the map of all properties' key value pairs from myproperty.properties.
Now you can inject this AppConfig class in whichever class you like.
Like
public class A{
.
.
#Autowired
private AppConfig appConfig;
.
.
private void method1(){
int age= appConfig.getEnv().getProperty("user.age");
}
This way you can separate property-reading logic at one place, and make your code more modular.
I am trying to simple spring program that has a class named PersistenceConfig annotated with #Configuration
#Configuration
#PropertySource("classpath:application.properties")
public class PersistanceConfig {
#Value("${dbPassword}")
private String dbPassword;
// Set of Beans and Code
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dataSource.setUrl("jdbc:sqlserver://localhost;databaseName=GovernmentPayment;integratedSecurity=false;");
dataSource.setUsername("sa");
dataSource.setPassword(dbPassword);
return dataSource;
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
When i run my program, the value dbPassword is always null but if i try to read the same value inside one my Controllers it reads the value without any issues.
I have tried autowiring Environment variable and using it instead of #Value but it didn't work either. (Spring didn't inject value to the Environment Variable)
I am using Spring 4
What is basically want is to externalize the database username and password in a separate property file.
i don't see any problem with given code.i wrote a simple unit test to your class to prove it works.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes=PersistanceConfig.class)
public class PersistanceConfigTest {
#Autowired
private DriverManagerDataSource dataSource;
private final String password = "mydbPassword";
#Test
public void testDriverManagerDataSourcePassword() {
System.out.println("dataSource Password :: " + dataSource.getPassword());
assertNotNull(dataSource);
assertTrue(password.equals(dataSource.getPassword()));
}
}
assuming you have application.properties in src/main/resources and dbPassword=mydbPassword is presented in that file.
Credit goes to Chad Darby
This is an issue with Spring versions.
If you are using Spring 4.2 and lower, you will need to add the code in marked with(**).
package com.luv2code.springdemo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
#Configuration
// #ComponentScan("com.luv2code.springdemo")
#PropertySource("classpath:sport.properties")
public class SportConfig {
// add support to resolve ${...} properties
**#Bean
public static PropertySourcesPlaceholderConfigurer
propertySourcesPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}**
// define bean for our sad fortune service
#Bean
public FortuneService sadFortuneService() {
return new SadFortuneService();
}
// define bean for our swim coach AND inject dependency
#Bean
public Coach swimCoach() {
SwimCoach mySwimCoach = new SwimCoach(sadFortuneService());
return mySwimCoach;
}
}
````
In Spring 4.3 and higher, they removed this requirement. As a result, you don't need this code.
I have solved this by moving that two annotations to the main file.
package com.luv2code.springdemo;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan(basePackages = "com.luv2code.springdemo.SportConfig")
public class SwimJavaConfigDemoApp {
public static void main(String[] args) {
// read spring config java class
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(SportConfig.class);
// get the bean from spring container
Coach theCoach = context.getBean("swimCoach", Coach.class);
// call a method on the bean
System.out.println(theCoach.getDailyWorkout());
// call method to get the daily fortune
System.out.println(theCoach.getDailyFortune());
// close the context
context.close();
}
}
Configure the main file.
Use component scan and specified the path to the cofig class.
Next, write some Bean's to the config file.
package com.luv2code.springdemo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
public class SportConfig {
// define a bean for sad fortune service
#Bean
public FortuneService sadFortuneService() {
return new SadFortuneService();
}
// define bean for our swim coach and inject dependency
#Bean
public Coach swimCoach() {
return new SwimCoach(sadFortuneService());
}
}
For futher learning : Component Scan.
In my repository there are file-properties with this var:
wizard.start.scriptNameAndroid=install-android.bat
This is a part of my file spring-businss.xml:
<bean id="wizardService" class="business.services.WizardServiceImpl">
<property name="nameFileAndroid" value="${wizard.start.scriptNameAndroid}"/>
</bean>
This is my class Java
public class WizardServiceImpl implements WizardService {
private static String nameFileAndroid="";
[...]
public String getNameFileAndroid() {
return nameFileAndroid;
}
public void setNameFileAndroid(String nameFileAndroid) {
this.nameFileAndroid = nameFileAndroid;
}
}
When i use the variable nameFileAndroid the program take always the value that i set into the class.
How can i do priority of file file-properties?
Why you don't Inject it using:
#Value("${wizard.start.scriptNameAndroid}")
private static String nameFileAndroid;
it will take value from your properties file.
If that variable is in .properties file you can refer to its value like this:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
#ComponentScan(basePackages = { "business.services.*" })
#PropertySource("classpath:file.properties")
public class WizardServiceImpl implements WizardService {
#Autowired
private Environment enviro;
private static String nameFileAndroid = enviro.getProperty("wizard.start.scriptNameAndroid");
}
Another way
#ComponentScan(basePackages = { "business.services.*" })
#PropertySource("classpath:file.properties")
public class WizardServiceImpl implements WizardService {
#Value("${wizard.start.scriptNameAndroid}")
private static String nameFileAndroid;
//Register bean to enable ${} value wiring
#Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
}
Or if you still prefer XML way:
<context:property-placeholder location="resources/file.properties" />
Hope i helped. :)
I've a SpringBootApplication and I want read a value from my property file.
My #SpringBootApplication class is this:
#SpringBootApplication
#ComponentScan(basePackages = "it.test")
#PropertySource("classpath:application.properties")
public class Application {
private static Logger log = LogManager.getLogger();
#Value("${server.modem.delay}")
private int modemSmsDelay;
#Order(Ordered.HIGHEST_PRECEDENCE)
#Bean(initMethod = "start", destroyMethod = "stop")
public Service smsService() {
settings();
Service service = Service.getInstance();
return service;
}
private void settings() {
log.debug("Delay per invio sms " + modemSmsDelay +"ms");
Settings.gatewayDispatcherYield = modemSmsDelay;
}
}
Unfortunately in in method called "settings" the value of property modemSmsDelay is 0 also if in my application.properties file it's 1000.
In other parts of my app I can read values without problems.
==== UPDATE =====
I solved the problem. Infact my code works, is not needed #PostConstruct to make #Value tag work, also if it's desiderable in several circustances.
I had a problem in my Spring configuration that prevented the execution of all annotation as #PostConstruct,#Autowire, etc.
I noticed this from log where Spring printed a Warning message.
Try putting the #PostConstruct annotation on your settings() method rather than calling it from the constructor. This will cause the method to be called automagically after the constructor exits.
This works for me :
#Resource private Environment environment;
import javax.annotation.Resource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import my.beautiful.code.SomeClient;
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Resource
private Environment environment;
#Override
protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Bean(name = "someClient")
public SomeClient loadSomeClient() {
SomeClient bean = new SomeClient();
...
bean.setHeaderContentType(environment.getProperty("contentType"));
bean.setRestUrl(environment.getProperty("rest.url"));
...
return bean;
}
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
}
And in my application.properties
contentType=some_value
rest.url=http://localhost/....
HTH