Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 277 Vote(s) - 3.52 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How can I inject a property value into a Spring Bean which was configured using annotations?

#11
Use Spring's "PropertyPlaceholderConfigurer" class

A simple example showing property file read dynamically as bean's property

<bean id="placeholderConfig"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/classes/config_properties/dev/database.properties</value>
</list>
</property>
</bean>

<bean id="devDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${dev.app.jdbc.driver}"/>
<property name="jdbcUrl" value="${dev.app.jdbc.url}"/>
<property name="user" value="${dev.app.jdbc.username}"/>
<property name="password" value="${dev.app.jdbc.password}"/>
<property name="acquireIncrement" value="3"/>
<property name="minPoolSize" value="5"/>
<property name="maxPoolSize" value="10"/>
<property name="maxStatementsPerConnection" value="11000"/>
<property name="numHelperThreads" value="8"/>
<property name="idleConnectionTestPeriod" value="300"/>
<property name="preferredTestQuery" value="SELECT 0"/>
</bean>

Property File

dev.app.jdbc.driver=com.mysql.jdbc.Driver

dev.app.jdbc.url=jdbc:mysql://localhost:3306/addvertisement

dev.app.jdbc.username=root

dev.app.jdbc.password=root
Reply

#12
You also can annotate you class:

@PropertySource("classpath:/com/myProject/config/properties/database.properties")

And have a variable like this:

@Autowired
private Environment env;

Now you can access to all your properties in this way:

env.getProperty("database.connection.driver")
Reply

#13
There is a new annotation `@Value` in *Spring 3.0.0M3*. `@Value` support not only `#{...}` expressions but `${...}` placeholders as well
Reply

#14
Personally I love this new way in Spring 3.0 [from the docs][1]:

private @Value("${propertyName}") String propertyField;

No getters or setters!

With the properties being loaded via the config:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="classpath:propertyFile.properties" name="propertiesBean"/>

To further my glee I can even control click on the EL expression in IntelliJ and it brings me to the property definition!

There's also the totally **non xml version**:

@PropertySource("classpath:propertyFile.properties")
public class AppConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}


[1]:

[To see links please register here]

Reply

#15
I think it's most convenient way to inject properties into bean is setter method.

Example:

package org.some.beans;

public class MyBean {
Long id;
String name;

public void setId(Long id) {
this.id = id;
}

public Long getId() {
return id;
}

public void setName(String name) {
this.name = name;
}

public String getName() {
return name;
}
}

Bean xml definition:

<bean id="Bean1" class="org.some.beans.MyBean">
<property name="id" value="1"/>
<property name="name" value="MyBean"/>
</bean>

For every named `property` method `setProperty(value)` will be invoked.

This way is especially helpful if you need more than one bean based on one implementation.

For example, if we define one more bean in xml:

<bean id="Bean2" class="org.some.beans.MyBean">
<property name="id" value="2"/>
<property name="name" value="EnotherBean"/>
</bean>

Then code like this:

MyBean b1 = appContext.getBean("Bean1");
System.out.println("Bean id = " + b1.getId() + " name = " + b1.getName());
MyBean b2 = appContext.getBean("Bean2");
System.out.println("Bean id = " + b2.getId() + " name = " + b2.getName());

Will print

Bean id = 1 name = MyBean
Bean id = 2 name = AnotherBean

So, in your case it should look like this:

@Repository("personDao")
public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {

Long maxResults;

public void setMaxResults(Long maxResults) {
this.maxResults = maxResults;
}

// Now use maxResults value in your code, it will be injected on Bean creation
public void someMethod(Long results) {
if (results < maxResults) {
...
}
}
}
Reply

#16
Spring way:
`private @Value("${propertyName}")
String propertyField;`

is a new way to inject the value using Spring's "PropertyPlaceholderConfigurer" class.
Another way is to call

java.util.Properties props = System.getProperties().getProperty("propertyName");

Note: For @Value, you can not use **static** propertyField, it should be non-static only, otherwise it returns null. To fix it a non static setter is created for the static field and @Value is applied above that setter.

Reply

#17
As mentioned `@Value` does the job and it is quite flexible as you can have spring EL in it.

Here are some examples, which could be helpful:


//Build and array from comma separated parameters
//Like currency.codes.list=10,11,12,13
@Value("#{'${currency.codes.list}'.split(',')}")
private List<String> currencyTypes;

Another to get a `set` from a `list`

//If you have a list of some objects like (List<BranchVO>)
//and the BranchVO has areaCode,cityCode,...
//You can easily make a set or areaCodes as below
@Value("#{BranchList.![areaCode]}")
private Set<String> areas;

You can also set values for primitive types.

@Value("${amount.limit}")
private int amountLimit;

You can call static methods:


@Value("#{T(foo.bar).isSecurityEnabled()}")
private boolean securityEnabled;

You can have logic

@Value("#{T(foo.bar).isSecurityEnabled() ? '${security.logo.path}' : '${default.logo.path}'}")
private String logoPath;






Reply

#18
You can do this in Spring 3 using EL support. Example:

@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }

@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { ... }

`systemProperties` is an implicit object and `strategyBean` is a bean name.

One more example, which works when you want to grab a property from a `Properties` object. It also shows that you can apply `@Value` to fields:

@Value("#{myProperties['github.oauth.clientId']}")
private String githubOauthClientId;

Here is a [blog post][1] I wrote about this for a little more info.

[1]:

[To see links please register here]

Reply

#19
Easiest way in Spring 5 is to use `@ConfigurationProperties` here is example

[To see links please register here]

Reply

#20
use @PropertySource("classpath:XX.properties") on your configuration class.
XX=file_name
[![enter image description here][1]][1]


[1]:
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through