Initialize a string with data from property file in controller - spring

I would like to Initialize a string with data from a property file in a spring controller:
#Controller
public class MyController {
private string dbName;
.....
....
}
and in my property file: (myApp.properties)
dbName=EMPLOYEE
I found an example here but in the example of sun, they use an init() method. But where should I call my init() method as there is no constructor of the Controller

You can move the configuration into a different class, initialize that class through spring XML definition like this :
<bean id="configuration" class="examples.Configuration">
<property name="dbNAme" value="EMPLOYEE">
</bean>
create a class like this :
public class Configuration {
public string dbName;
}
then reference it from your code.
#Controller
public class MyController {
#Autowired
private Configuration config;
}

Related

I want to load a specific class based on a flag instead of loading two class and using one the required in Springs

In configurations I have a flag isFlagEnabled.
So I have to read the flag from spring config and based on that I want to execute specific class A or B . Meaning I want to load A class only when isFlagEnabled is true and similarly load class B only when isFlagEnabled is false.
I have written the below code but i am stuck when ingesting .
public interface MediatorInt {
public void init();
}
class A implements MediatorInt {
init() { It does some task }
}
class B implements MediatorInt {
init(){ It does some task }
}
public class MasterNewGenImpl {
#Autowired
#Qualifier("config")
private Configuration config;
#Autowired
MediatorInt mediatorInt;
private final Logger logger = Logger.getLogger(getClass());
public void startService() {
mediatorInt.init();
}
}
context.xml file
<context:component-scan base-package="com.ca"/>
<bean id="config" class="com.ca.configuration.ConfigImplementation"/>
<bean id="masterSlave" class="com.ca.masterslave.A"/>
<bean id="systemState" class="com.ca.masterslave.B"/>
<bean id="masterSlaveNewGen" class="com.ca.masterslave.MasterNewGenImpl">
<property name = "mediatorOrMasteSlave" value="#{config.getMediatorMode() == 'true' ? 'systemState' : 'masterSlave'}" />
</bean>
So now i am not getting how to inject specific object based on the config flag . I want to make it through Lazy-init so that other object will not get loaded when its not required .
I greatly appreciate the suggestions.
If you are okay with spring scanning both the implementations, then you can select the needed one using #Qualifier. If you want spring not to scan some class based on a property, You can use #Conditional
class SomeCondition implements Condition {
#Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String isFlagEnabled = context.getEnvironment().getProperty("isFlagEnabled");
return isFlagEnabled.equals("true"));
}
}
#Configuration
#Conditional(value = SomeCondition.class)
class A implements MediatorInt {
init() { It does some task }
}
In the above config, class A is scanned only if matches() in SomeCondition class returns true, where you can define the condition.
You can use
#Autowired
#Qualifier( "systemState" )
MediatorInt systemSateMeidator;
#Autowired
#Qualifier( "masterSlave" )
MediatorInt masterSateMeidator;
With #Qualifier you are instructing spring on how to fulfill your component request.

how to load spring bean from another class

I have loaded "myspring.xml" in web.xml using context-param
in "myspring.xml" I have written bean to which I have passed arguments as constructor argument
<bean id="abc" class="com.Hello">
<constructor-arg ref="dataSource"/>
<constructor-arg value= “dummy data”/>
</bean>
in Hello bean I have initialized constructor as ,
public class Hello{
public Hello(datasource,dummydata){
}
public void methodFromHelloBean(){
// use here dummydata from constructor
}
}
Here , 'Hello' bean is getting initialized at server startup, as I defined in web.xml and it is working fine.
My question is -
I am working on exisitng applciation.
I want to call methodFromHelloBean() inside my another class say MyService class.
How I can call the method in MyService class.
One way i know is using applicationContext.
But in my existing application I have not seen any bean loaded using application-context path.
what is other way , how I can initialize 'Hello' bean from 'MyService' class.
Do I need to pass parameters to constructors while initializing & how.
Thanks in advance.
Let's suppose we have MyService a class whose bean instance consumes some method methodFromHelloBean from abc, the Hello bean.
public class Hello {
private boolean cacheInitialized;
public void methodFromHelloBean(Object param) {
if (!cacheInitialized) {
initializeCache(param);
cacheInitialized = true;
}
// do whatever you please with cache.
}
private void initializeCache(Object param) {
// TODO
}
}
public class MyService {
#Autowired
private Hello abc;
public void someMethod() {
// determine which parameters to pass to abc
Object param = ...
abc.methodFromHelloBean(param);
}
}

How to directly display a property value defined via PropertySourcesPlaceholderConfigurer in a jsp (Spring framework)?

I have the following configuration in Spring application context.
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="props">
<list>
<value>file://${user.home}/myConfig.properties</value>
</list>
</property>
</bean>
let's say I want to display a value (e.g : app.url.secret) defined as a property in the myConfig.properties file, directly in a jsp. How can I achieve that ?
thanks in advance for your help
You will have to get it to your model in some way:
One approach will be to use a PropertyHolder this way:
#Component
public class PropertyHolder {
#Value("${myprop}")
private String myProperty;
//getters and setters..
}
In your controller:
#Controller
public class MyController {
#Autowired private PropertyHolder propertyHolder;
#ModelAttribute
public void setModelAttributes(Model model) {
model.put("myprops", propertyHolder);
}
....rest of your controller..
}
then you have access to myprops in your jsp - myprops.myProperty
Firstly populate your model with the property value on your controller, then return a view that resolves to your JSP
You can use #Value annotation to inject the property to your controller
#Controller
public class MyController {
#Value("${app.url.secret}") private String urlSecret;
#RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("urlSecret", urlSecret);
// assuming this will resolve to hello.jsp
return "hello";
}
}
Then on your hello.jsp
<%# page ... %>
<html>
...
The secret url is: ${urlSecret}

Where to store config info for spring mvc 3.x

Where is a good place to store custom config info in spring mvc 3.x and how would I access that info globally via any controller?
Is there a built in config manager?
I assume 'custom config' means a configuration file the code reads / you / your operations team can update?
One easy solution is to use spring beans xml configuration file and deploy your war in exploded fashion.
Create a configuration java class:
// File: MyConfig.java ------------------------------------
public class MyConfig {
private String supportEmail;
private String websiteName;
// getters & setters..
}
Configure the class as a Spring bean and set its properties on your spring beans xml file (can also create a new file and use <import resource="..."/>):
// File: root-context.xml ----------------------------------------
<beans ...>
...
<bean class="com.mycompany.MyConfig">
<property name="supportEmail" value="support#mycompany.com"/>
<property name="websiteName" value="Hello Site"/>
</bean>
...
</beans>
Inject your configuration class (eg: in a controller)
// File: HelloController.java ------------------------------------
#Controller
#RequestMapping("/hello")
public class HelloController {
#Autowired MyConfig config;
// ...
}
However updates to the configuration would require re-deploy / server restarts
You can also use <context:property-placeholder>.
It looks like this.
myapp.properties:
foo=bar
spring beans xml:
<context:property-placeholder location="classpath:myapp.properties"/>
Or
<context:property-placeholder location="file:///path/to/myapp.properties"/>
Controller:
import org.springframework.beans.factory.annotation.Value;
...
#Controller
public class Controller {
#Value("${foo}")
private String foo;
If you want to get properties programmatically, you can use Environment with #PropertySource.
Configuration:
#Configuration
#PropertySource("classpath:myapp.properties")
public class AppConfig {
#Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
Controller:
#Controller
public class Controller {
#Value("${foo}")
private String foo;
#Autowired
private Environment env;
#RequestMapping(value = "dosomething")
public String doSomething() {
env.getProperty("foo");
...
}
Hope this helps.

Autowired not working as expected

I'm using Spring Roo and want to access a bean within of Controller class which has following configuration in applicationContext.xml:
<bean class="com.reservation.jobs.Configuration" id="jobsConfiguration" autowire="byType">
<property name="skipWeeks" value="4" />
</bean>
The configuration class itself is:
package com.reservation.jobs;
public class Configuration {
private int skipWeeks;
public void setSkipWeeks(int value) {
System.out.println("SkipWeeks set auf: " + value);
this.skipWeeks = value;
}
public int getSkipWeeks() {
return this.skipWeeks;
}
}
In my Controller I thought that a simple Autowired annotation should do the job
public class SomeController extends Controller {
#Autowired
private com.reservation.jobs.Configuration config;
}
During startup Spring prints the message within the setSkipWeeks method. Unfortunately whenever I call config.getSkipWeeks() within the controller it returns 0.
Have I to use the getBean method of the ApplicationContext instance or is there some better way?
autowire="byType" is redundant. It indicates that fields of the Configuration class should be autowired, and you have just one primitive. So remove that attribute.
Apart from that, config.getSkipWeeks() must return 4 unless:
you are using a different instance (made by you with new)
you have called the setter somewhere with a value of 0

Resources