How to load/access a bean (#Resource) in a custom Velocity tool - java

I realize this is a slightly funky thing to need to do, but I'm trying to access my Spring messageSource bean from a custom Velocity tool.
In most of our codebase, I'm able to just set up a member variable and load it like this:
#Resource(name = "messageSource")
private AbstractMessageSource _msgSource;
However, in this circumstance, this doesn't load the bean, I'm assuming because the Velocity tools get instantiated in a way that doesn't allow normal bean loading to occur. Or it doesn't want to initialize the bean for an application scoped Velocity tool.
The tool is set up in the toolbox.xml as follows:
<tool>
<key>calendarTool</key>
<scope>application</scope>
<class>...</class>
</tool>
I haven't been able to find anything online that explains either how to do this or why it doesn't work.

What I've done is in the code where I render the Velocity template, I retrieve the message source from the applicationContext using applicationContext.getBean("messageSource") and then I put that MessageSource directly into the the VelocityContext that I use to render my templates under the key "messageSource" :
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("messageSource", applicationContext.getBean("messageSource"));
Then, anytime I want to render a message key, say in an HTML email, it looks something like :
<td>messageSource.getMessage("my.message.key", null, $locale)</td>
where $locale is a java.util.Locale object that I've also manually placed in the VelocityContext. If I ever need any arguments to the message, then I use the list tool I've put in the context to get an array from the list of arguments I'll typically create right there in the template. As a side note, you can use the helper methods in the
org.springframework.ui.velocity.VelocityEngineUtils class to help you out with rendering Velocity templates in your controllers or webflow code, or wherever else you may be rendering templates.

Not sure why it doesn't work, but have you tried retrieving it without annotations, something like:
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
AbstractMessageSource _msgSource = (AbstractMessageSource )ctx.getBean("messageSource");

Related

To provide nicer logging when a Spring property is invalid

Using a application.properties file my Spring Boot app can use some property values in it. A way to make sure a mandatory value must present is to add an annotation #Value for the property. The problem with this is the app fails miserably if the property value is not there in the properties file.
I am after a nicer less horrible way to say printing out a log line about "Property A is missing" instead of a whole stack trace. Is there a way to do this while still using #Value to initialise the properties? For example, property A is mandatory, an error is logged before app exits; property B is missing but not mandatory, a warning is logged and app continues.
If you can identify all property, then you can write a method in Application class with #Postconstruct, and inside your method, you can manually validate and log them
#Autowired
private Environment environment;
#PostConstruct
private void validateProperties() {
environment.getProperty(key);
.....
......
}
Alternatively, you can write your custom EnvironmentPostProcessor, and iterate all properties and log whichever is null/empty.
As you're using spring-boot consider creating a #ConfigurationProperties class rather than using the #Value annotation.
By doing that you can do your validations using Bean Validation, also in the same class, you can implement the interface InitializingBean and add extra validations/log messages as you with.
Follow this link on Spring's official docs to read more about #ConfigurationProperties.

What does getBean() method do here?

What is the getBean() method doing here and how does it work in a program?
ApplicationContext aplicntxt = new
ClassPathXmlApplicationContext("springconfig.xml");
Hello h = (Hello) aplicntxt.getBean("springconfig.xml");
h.display();
Hello h2 = new Hello(); //if I write this
h2.display();
My question is why h2.display retrieves null value and h.display retrieves the stored values through springconfig.xml?
Please tell me what does
ApplicationContext aplicntxt = new ClassPathXmlApplicationContext("springconfig.xml");
do first?
Are all the values of xml file stored to the pojo class setters at first step?
Then we are storing the values to an object h
by doing
Hello h = (Hello) aplicntxt.getBean("springconfig.xml");
Your question is essentially "How does spring work", this is covered extensively by the official documentation
The following creates all the beans defined by the springconfig.xml, that is it creates objects of the given types, and injects any properties you've defined, depending on your exact configuration it may also do things like package scanning, annotation processing etc.
ApplicationContext aplicntxt= new ClassPathXmlApplicationContext("springconfig.xml");
XML
<bean class="org.example.Hello" id="foo" />
<bean class="org.example.Hello" id="bar" />
This would create an objects of type Hello and tag them with the IDs "foo" and "bar"
All the beans are stored against their IDs for later retrieval via getBean(), note this takes the bean ID or name, not the XML file.
Hello h = (Hello) aplicntxt.getBean("foo");
What you are doing in code is called Spring Dependency Injection which let you define application beans and inject them when you need. like getBean() method that you use in your code which inject specific bean from XML file.
From spring doc
The interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata. The configuration metadata is represented in XML, Java annotations, or Java code. It allows you to express the objects that compose your application and the rich interdependencies between such objects.
Several implementations of the ApplicationContext interface are supplied out-of-the-box with Spring. In standalone applications it is common to create an instance of ClassPathXmlApplicationContext or FileSystemXmlApplicationContext. While XML has been the traditional format for defining configuration metadata you can instruct the container to use Java annotations or code as the metadata format by providing a small amount of XML configuration to declaratively enable support for these additional metadata formats.
Now Your Question and its simple ApplicationContext activates the object(it is eager container) and looks for the beans declared so the objects are loaded whenever it is called.
Now consider if you have two beans , and you need one of them you will find that bean by using ctx.getBean("beanId") to load instance and to provide data declared with this bean where beanId will tell which object to load.
consider following example
<bean id="a" class="package.Hello" />
//here it will look for bean name and then loads the class
Now when You call it like
ApplicationContext ctx=new ClassPathXMLApplicationContext("configuration.xml");
//will look for configuration.xml bean file if it is not in path then throw execption.
now
Hello hello=ctx.getBean("a");
// if configuration.xml contains any bean named "a" and holds reference to class(hello) load it immediately and return object of that class
is same as
Hello hello=new Hello();
hello.method();
and it is creating object of Hello class by using xml
From looking at this quickly, it appears that this code uses spring to initialize the Hello object with the values specified in the spring bean found in the xml file (I'm assuming that's what's in the filr, but I could be more specific if you post it).. When you create a second hello object you are using the constructor's default value for display, which is null.

using and understanding the picoContainer

I am trying to use the picoContainer in my project.
I know very little about it but want to give it a shot.
As I understand, I have to create a picoContainer and registercomponents with it.
I did this
public static PicoContainer getPicoContainer(){
final MutablePicoContainer pico = new DefaultPicoContainer();
pico.registerComponentImplementation(X.class);
pico.registerComponentImplementation(A.class);
pico.registerComponentImplementation(C.class);
pico.registerComponentImplementation(V.class);
pico.registerComponentImplementation(T.class);
pico.registerComponentImplementation(D.class);
return pico;
}
Now my problem is that for any component to get the other component, it needs a handle on pico.
To access any component it needs to do this
A juicer = pico.getComponent(A.class);
So, in the constructor for each of them, I need to pass in the pico object? I can easily replace this with a factory. What's the point then? I'm sure i'm missing something here.
Would appreciate any help.
Common pattern is to have somewhere a factory for the main container.
For stand-alone app it probably will be "public static void main()" entry point, for web app it will be front controller servlet or filter or context listener (pico has support class for listener case).
So at the entry point you configure the container in a way you mentioned above "public static PicoContainer getPicoContainer()" then you need to pass control to an entry point in the container. The nice way is to have at least one container's component to implement lifecycle interface (http://picocontainer.codehaus.org/lifecycle.html) then you start() the container and have everything wired up.
In normal case you should never access the container itself beside entry configuration and such things as special factories or transaction demarcation etc.

Spring MVC send properties via controller to a xml declared bean

I wanted to know if I can pass a property to a bean I declared on a xml configuration file (for example on the applicationContext.xml):
<bean id="captchaVerifierFilter" class="org.abc.filter.CaptchaVerifierFilter"
p:useProxy="false"
p:proxyPort=""
p:proxyHost=""
p:failureUrl="/abc/main/loginfailed"
p:captchaCaptureFilter-ref="captchaCaptureFilter"
/>
I want to use the captchaVerifierFilter bean to test if a captcha is valid or not. Then I can set the failureUrl property to url "add-record" and redirect to that jsp.
How can I send a property (like failureUrl for example) through a controller. Is this possible? What should I code on the controller if it's possible?
Any idea? Thank you very much!
I think you should define both the success and the failure url as properties in your configuration and then let the filter decide which way to go.
You can change the properties of the bean if you make it accessible (by making it public or with a setter) but that is probably not want you want since it changes the property for the single bean instance in the application context which is used by several threads concurrently.
Best regards
Hacim
By default the beans in the context are in singleton scope. So when you set the value for the property failureUrl in one controller, another controller will also see this new value when it gets the bean from the context.

Can I replace a Spring bean definition at runtime?

Consider the following scenario. I have a Spring application context with a bean whose properties should be configurable, think DataSource or MailSender. The mutable application configuration is managed by a separate bean, let's call it configuration.
An administrator can now change the configuration values, like email address or database URL, and I would like to re-initialize the configured bean at runtime.
Assume that I can't just simply modify the property of the configurable bean above (e.g. created by FactoryBean or constructor injection) but have to recreate the bean itself.
Any thoughts on how to achieve this? I'd be glad to receive advice on how to organize the whole configuration thing as well. Nothing is fixed. :-)
EDIT
To clarify things a bit: I am not asking how to update the configuration or how to inject static configuration values. I'll try an example:
<beans>
<util:map id="configuration">
<!-- initial configuration -->
</util:map>
<bean id="constructorInjectedBean" class="Foo">
<constructor-arg value="#{configuration['foobar']}" />
</bean>
<bean id="configurationService" class="ConfigurationService">
<property name="configuration" ref="configuration" />
</bean>
</beans>
So there's a bean constructorInjectedBean that uses constructor injection. Imagine the construction of the bean is very expensive so using a prototype scope or a factory proxy is not an option, think DataSource.
What I want to do is that every time the configuration is being updated (via configurationService the bean constructorInjectedBean is being recreated and re-injected into the application context and dependent beans.
We can safely assume that constructorInjectedBean is using an interface so proxy magic is indeed an option.
I hope to have made the question a little bit clearer.
Here is how I have done it in the past: running services which depend on configuration which can be changed on the fly implement a lifecycle interface: IRefreshable:
public interface IRefreshable {
// Refresh the service having it apply its new values.
public void refresh(String filter);
// The service must decide if it wants a cache refresh based on the refresh message filter.
public boolean requiresRefresh(String filter);
}
Controllers (or services) which can modify a piece of configuration broadcast to a JMS topic that the configuration has changed (supplying the name of the configuration object). A message driven bean then invokes the IRefreshable interface contract on all beans which implement IRefreshable.
The nice thing with spring is that you can automatically detect any service in your application context that needs to be refreshed, removing the need to explicitly configure them:
public class MyCacheSynchService implements InitializingBean, ApplicationContextAware {
public void afterPropertiesSet() throws Exception {
Map<String, ?> refreshableServices = m_appCtx.getBeansOfType(IRefreshable.class);
for (Map.Entry<String, ?> entry : refreshableServices.entrySet() ) {
Object beanRef = entry.getValue();
if (beanRef instanceof IRefreshable) {
m_refreshableServices.add((IRefreshable)beanRef);
}
}
}
}
This approach works particularly well in a clustered application where one of many app servers might change the configuration, which all then need to be aware of. If you want to use JMX as the mechanism for triggering the changes, your JMX bean can then broadcast to the JMS topic when any of its attributes are changed.
I can think of a 'holder bean' approach (essentially a decorator), where the holder bean delegates to holdee, and it's the holder bean which is injected as a dependency into other beans. Nobody else has a reference to holdee but the holder. Now, when the holder bean's config is changed, it recreates the holdee with this new config and starts delegating to it.
You should have a look at JMX. Spring also provides support for this.
Spring 2.0.x
Spring 2.5.x
Spring 3.0.x
Further updated answer to cover scripted bean
Another approach supported by spring 2.5.x+ is that of the scripted bean. You can use a variety of languages for your script - BeanShell is probably the most intuitive given that it has the same syntax as Java, but it does require some external dependencies. However, the examples are in Groovy.
Section 24.3.1.2 of the Spring Documentation covers how to configure this, but here are some salient excerpts illustrating the approach which I've edited to make them more applicable to your situation:
<beans>
<!-- This bean is now 'refreshable' due to the presence of the 'refresh-check-delay' attribute -->
<lang:groovy id="messenger"
refresh-check-delay="5000" <!-- switches refreshing on with 5 seconds between checks -->
script-source="classpath:Messenger.groovy">
<lang:property name="message" value="defaultMessage" />
</lang:groovy>
<bean id="service" class="org.example.DefaultService">
<property name="messenger" ref="messenger" />
</bean>
</beans>
With the Groovy script looking like this:
package org.example
class GroovyMessenger implements Messenger {
private String message = "anotherProperty";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message
}
}
As the system administrator wants to make changes then they (or you) can edit the contents of the script appropriately. The script is not part of the deployed application and can reference a known file location (or one that is configured through a standard PropertyPlaceholderConfigurer during startup).
Although the example uses a Groovy class, you could have the class execute code that reads a simple properties file. In that manner, you never edit the script directly, just touch it to change the timestamp. That action then triggers the reload, which in turn triggers the refresh of properties from the (updated) properties file, which finally updates the values within the Spring context and off you go.
The documentation does point out that this technique doesn't work for constructor-injection, but maybe you can work around that.
Updated answer to cover dynamic property changes
Quoting from this article, which provides full source code, one approach is:
* a factory bean that detects file system changes
* an observer pattern for Properties, so that file system changes can be propagated
* a property placeholder configurer that remembers where which placeholders were used, and updates singleton beans’ properties
* a timer that triggers the regular check for changed files
The observer pattern is implemented by
the interfaces and classes
ReloadableProperties,
ReloadablePropertiesListener,
PropertiesReloadedEvent, and
ReloadablePropertiesBase. None of them
are especially exciting, just normal
listener handling. The class
DelegatingProperties serves to
transparently exchange the current
properties when properties are
updated. We only update the whole
property map at once, so that the
application can avoid inconsistent
intermediate states (more on this
later).
Now the
ReloadablePropertiesFactoryBean can be
written to create a
ReloadableProperties instance (instead
of a Properties instance, as the
PropertiesFactoryBean does). When
prompted to do so, the RPFB checks
file modification times, and if
necessary, updates its
ReloadableProperties. This triggers
the observer pattern machinery.
In our case, the only listener is the
ReloadingPropertyPlaceholderConfigurer.
It behaves just like a standard spring
PropertyPlaceholderConfigurer, except
that it tracks all usages of
placeholders. Now when properties are
reloaded, all usages of each modified
property are found, and the properties
of those singleton beans are assigned
again.
Original answer below covering static property changes:
Sounds like you just want to inject external properties into your Spring context. The PropertyPlaceholderConfigurer is designed for this purpose:
<!-- Property configuration (if required) -->
<bean id="serverProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<!-- Identical properties in later files overwrite earlier ones in this list -->
<value>file:/some/admin/location/application.properties</value>
</list>
</property>
</bean>
you then reference the external properties with Ant syntax placeholders (that can be nested if you want from Spring 2.5.5 onwards)
<bean id="example" class="org.example.DataSource">
<property name="password" value="${password}"/>
</bean>
You then ensure that the application.properties file is only accessible to the admin user and the user running the application.
Example application.properties:
password=Aardvark
Or you could use the approach from this similar question and hence also my solution:
The approach is to have beans that are configured via property files and the solution is to either
refresh the entire applicationContext (automatically using a scheduled task or manually using JMX) when properties have changed or
use a dedicated property provider object to access all properties. This property provider will keep checking the properties files for modification. For beans where prototype-based property lookup is impossible, register a custom event that your property provider will fire when it finds an updated property file. Your beans with complicated lifecycles will need to listen for that event and refresh themselves.
You can create a custom scope called "reconfigurable" into the ApplicationContext. It creates and caches instances of all beans in this scope. On a configuration change it clears the cache and re-creates the beans on first access with the new configuration. For this to work you need to wrap all instances of reconfigurable beans into an AOP scoped proxy, and access the configuration values with Spring-EL: put a map called config into the ApplicationContext and access the configuration like #{ config['key'] }.
This is not something I tried, I am trying to provide pointers.
Assuming your application context is a subclass of AbstractRefreshableApplicationContext(example XmlWebApplicationContext, ClassPathXmlApplicationContext). AbstractRefreshableApplicationContext.getBeanFactory() will give you instance of ConfigurableListableBeanFactory. Check if it is instance of BeanDefinitionRegistry. If so you can call 'registerBeanDefinition' method. This approach will be tightly coupled with Spring implementation,
Check the code of AbstractRefreshableApplicationContext and DefaultListableBeanFactory(this is the implementation you get when you call 'AbstractRefreshableApplicationContext getBeanFactory()')
Option 1 :
Inject the configurable bean into the DataSource or MailSender. Always get the configurable values from the configuration bean from within these beans.
Inside the configurable bean run a thread to read the externally configurable properties (file etc..) periodically. This way the configurable bean will refresh itself after the admin had changed the properties and so the DataSource will get the updated values automatically.
You need not actually implement the "thread" - read : http://commons.apache.org/configuration/userguide/howto_filebased.html#Automatic_Reloading
Option 2 (bad, i think, but maybe not - depends on use case) :
Always create new beans for beans of type DataSource / MailSender - using prototype scope. In the init of the bean, read the properties afresh.
Option 3 :
I think, #mR_fr0g suggestion on using JMX might not be a bad idea. What you could do is :
expose your configuration bean as a MBean (read http://static.springsource.org/spring/docs/2.5.x/reference/jmx.html)
Ask your admin to change the configuration properties on the MBean (or provide an interface in the bean to trigger property updates from their source)
This MBean (a new piece of java code that you will need to write), MUST keep references of Beans (the ones that you want to change / inject the changed properties into). This should be simple (via setter injection or runtime fetch of bean names / classes)
When the property on the MBean is changed (or triggered), it must call the appropriate setters on the respective beans. That way, your legacy code does not change, you can still manage runtime property changes.
HTH!
You may want to have a look at the Spring Inspector a plug-gable component that provides programmatic access to any Spring based application at run-time. You can use Javascript to change configurations or manage the application behaviour at run-time.
Here is the nice idea of writing your own PlaceholderConfigurer that tracks the usage of properties and changes them whenever a configuration change occurs. This has two disadvantages, though:
It does not work with constructor injection of property values.
You can get race conditions if the reconfigured bean receives a
changed configuration while it is processing some stuff.
My solution was to copy the original object. Fist i created an interface
/**
* Allows updating data to some object.
* Its an alternative to {#link Cloneable} when you cannot
* replace the original pointer. Ex.: Beans
* #param <T> Type of Object
*/
public interface Updateable<T>
{
/**
* Import data from another object
* #param originalObject Object with the original data
*/
public void copyObject(T originalObject);
}
For easing the implementation of the function fist create a constructor with all fields, so the IDE could help me a bit. Then you can make a copy constructor that uses the same function Updateable#copyObject(T originalObject). You can also profit of the code of the constructor created by the IDE to create the function to implement:
public class SettingsDTO implements Cloneable, Updateable<SettingsDTO>
{
private static final Logger LOG = LoggerFactory.getLogger(SettingsDTO.class);
#Size(min = 3, max = 30)
private String id;
#Size(min = 3, max = 30)
#NotNull
private String name;
#Size(min = 3, max = 100)
#NotNull
private String description;
#Max(100)
#Min(5)
#NotNull
private Integer pageSize;
#NotNull
private String dateFormat;
public SettingsDTO()
{
}
public SettingsDTO(String id, String name, String description, Integer pageSize, String dateFormat)
{
this.id = id;
this.name = name;
this.description = description;
this.pageSize = pageSize;
this.dateFormat = dateFormat;
}
public SettingsDTO(SettingsDTO original)
{
copyObject(original);
}
#Override
public void copyObject(SettingsDTO originalObject)
{
this.id = originalObject.id;
this.name = originalObject.name;
this.description = originalObject.description;
this.pageSize = originalObject.pageSize;
this.dateFormat = originalObject.dateFormat;
}
}
I used it in a Controller for updating the current settings for the app:
if (bindingResult.hasErrors())
{
model.addAttribute("settingsData", newSettingsData);
model.addAttribute(Templates.MSG_ERROR, "The entered data has errors");
}
else
{
synchronized (settingsData)
{
currentSettingData.copyObject(newSettingsData);
redirectAttributes.addFlashAttribute(Templates.MSG_SUCCESS, "The system configuration has been updated successfully");
return String.format("redirect:/%s", getDao().getPath());
}
}
So the currentSettingsData which has the configuration of the application gonna have the updated values, located in newSettingsData. These method allows updating any bean without high complexity.

Categories

Resources