Finally had a need to configure Spring by java code

All of my projects already configured spring via the context xml files. I know they support configuration by @Configuration annotated java classes. I never used it, because I never had a need. The context file is simple and easy to understand. It also gives you one place to go to track down classes.

I have a properties file that sits on a webdav. Unfortunately, there is one per environment and I have to run some java code to determine which environment I am in before I can retrieve the file.

  • @Configuration Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime
  • @Bean Indicates that a method produces a bean to be managed by the Spring container.
  • jxportal() The default strategy for determining the name of a bean is to use the name of the Bean method
package com.appriss.justicexchange.springextension.configuration;

import com.appriss.justicexchange.commons.http.HttpUtils;
import com.appriss.justicexchange.commons.utility.Utility;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.Properties;

/**
 * Spring java configuration to instantiate webdav objects.
 * @author nshelton
 */
@Configuration
public class WebdavConfig {
    private static Logger log = LoggerFactory.getLogger(WebdavConfig.class);

    /**
     * Produces the jxportal.properties object from the webdav.
     * @return Properties object with jxportal.properties as it's contents
     */
    @Bean
    public Properties jxportal() {
        Properties webdav = new Properties();
        try {
            webdav.load(
                IOUtils.toInputStream(
                    HttpUtils.getResponse(Utility.getWebdavServer() + "/product/jxportal/config/jxportal.properties")));
        } catch (IOException e) {
            log.error("Unable to load /product/jxportal/config/jxportal.properties", e);
        }
        return webdav;
    }
}
About these ads
This entry was posted in Java, Spring. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s