Chris Love CNM | Tech Blog

Springsource has released the Javaconfig Framework as a core component of Spring 3.0. There is a trend in the industry to move from XML meta data toward using more annotation driven meta data. I say pick your poison, as one can mess up either.

I do like the readability of using Java code for configuration. Reading the Java classes used for the configuration has a shorter learning curve than reading XML files. Also I can directly unit test my configuration.

The Example

File Highlights

I have uploaded an exported eclipse project here. I am using eclipse m2eclipse and spring plugins, and I would recommend importing the project as a maven project.

The Java class used for configuration:

@Configuration
// spring config that loads the properties file
@ImportResource("classpath:/properties-config.xml")
public class AppConfig {

    /**
     * Using property 'EL' syntax to load values from the
     * jetProperties value
     */
    private @Value("#{jetProperties['jetBean.name']}") String name;
    private @Value("#{jetProperties['jetBean.price']}") Long price;
    private @Value("#{jetProperties['jetBean.url']}") URL url;

    /**
     * Create a jetBean within the Spring Application Context
     * @return a bean
     */
    public @Bean(name = "jetBean")
    JetBean jetBean() {
        JetBean bean = new JetBeanImpl();
        bean.setName(name);
        bean.setPrice(price);
        bean.setUrl(url);
        return bean;
    }

}

The highlights for this class:

  • @Configuration – Basic annotation for Java based configuration.
  • @ImportResource – Allows us to import a spring xml file to add more functionality to the configuration that this class is building.
  • @Value – Creates expression driven dependency injection.
  • @Bean – Create a bean managed by the spring container.

The properties-config.xml file:

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <!-- define the properties file to use -->
    <util:properties id="jetProperties"
        location="classpath:/jet.properties" />
</beans>

One line that matters. Line number 8. Create a java.util.Properties instance with values loaded from the supplied properties file.

Other files such as the POJO’s and properties files are included in the example. They are very vanilla, so I did not include them in the post. The test case has some changes in it.

public class JetBeanTest {

    @Test
    public void testJetBean() {
        // create the spring container using the AppConfig
        // @Configuration class
        ApplicationContext ctx =
              new AnnotationConfigApplicationContext(AppConfig.class);
        JetBean jetBean = ctx.getBean(JetBean.class);
        assertThat(jetBean.getName(), equalTo("Gulf Stream G550"));
        assertThat(jetBean.getPrice(), equalTo(Long.valueOf(60000000)));
        URL gulfstream;
        try {
            gulfstream =
                new URL("http://www.gulfstream.com/products/g550/");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            fail("error creating URL");
            throw new RuntimeException("error creating URL");
        }
        assertThat(jetBean.getUrl(), equalTo(gulfstream));
    }
}

The main change is the new class AnnotationConfigApplicationContext which drives the creation of the Spring application context via Java configuration.

Recap

Use @Configuration to annotate your configuration class. Mark your beans with @Bean. The following annotations are supported:

  • @Configuration
  • @Bean
  • @DependsOn
  • @Primary
  • @Lazy
  • @Import
  • @ImportResource
  • @Value

Using @Value with Spring Expression Language

Now starts the crazy cool stuff. The @Value can be used on fields, methods and parameters. Plus, Spring Expression Language (SpEL) defines the ‘value’ through the syntax #{ < SpEL expression > }. The syntax can get a bit harry, but is incredibly powerful. In this example I have used SpEL to load values from the javaProperties java.lang.Properties Object with syntax like:

// jetProperties java.lang.Properties bean in context.
// jetBean.name value in the property file
@Value("#{jetProperties['jetBean.name']}") String name;

Using @Value and SpEL gives you the functionality to do such things as: setting default values, accessing system level properties, logical operators, regex, mathematical operations.

To summarize as Uncle Ben said:

With great power there must come great responsibility.

Link to the example code here.

Much thanks to Chris Beams and his blog post on Springsource.

· · ·

Feb/10

23

Going Back to Pen and Paper

In the age of IPhones and Laptop computers I am starting to use paper again. Over the last two months I have been inundated with people, magazine articles and speakers at conferences telling me to use a notebook.

Most recently, while on my way to Philadelphia via US Airways, I read an article in their magazine that talked about going analog in a digital world, by David Hornik of ventureblog.com. He poignantly talked about how simple paper has such redeeming qualities, and how a bunch of tech entrepreneurs where using pen and paper.

Why is it that this all-star crowd of tech moguls had pushed aside the very digital domain about which they were so madly taking notes with pen and paper?

My ideas on the subject:

  • Does not run out of power, but alas you can loose your pen
  • Paper does not get viruses, but does not like coffee, as most electronics
  • Do not need to back up paper, but I am actually going to scan my notebook
  • No on button and ergo it is always on

The most interesting thing about capturing ideas on paper is that alot of people’s retension is higher. Also I am still killing trees in order to proof read anything at a super high level. Do not catch as many errors proof reading the written word on a computer screen as on paper. My guess is that because we where taught at a young informative age with pen and pad that our brains have a greater affinity for learning with the pen.

So today I am taking the leap and buying one of the trendy techy notepads, a moleskine.

You can read David Hornik;s blog post Pen and Paper are Mightier Than the Laptop that the US Airways Magazine article was based on.

·

Feb/10

23

Maintaining MSSQL Server Indexes

Working with a client who use MSSQL server for their ERP application, we noticed that their indexes where not being maintained. Not maintaining your indexes on tables that are very active, can lead to performance degredation. Monthly rebuilding and or regorganizing indexes can help with the overal table performance. See this reference for more information on why to maintain indexes.

The challenge we ran into was that their database contained hundreds of tables, and writing a SQL query to rebuild each table’s index would, how should I say, suck.

Stored procedures to the rescue! Needless to say this is not the first time a DBA had run accross this challenge. My client found a great nugget of stored procedure bliss located on sqlservercentral.com

Example of running the stored procedure:

EXEC dbo.spX_RebuildIndexes_Main ‘mydbname’, 0, 0, 1, 1, 4, 60000;

Here’s the definition of variables:

@databasename - If you only want to rebuild/reorganize a particular database
@maxfrag float - Only indexes with an avg fragmentation in percent > @maxfrag are inluded,
@maxdensity float - OR tables with an avg page space used in percent < @maxdensity are included
@online bit - If 1, REBUILD WITH ONLINE = ON (Enterpise or Developer) or REORGANIZE, else REORGANIZE IF @currentfrag < 30 ELSE REBUILD (IF no users)
@runrebuild bit - If 1, REBUILD/REORGANIZE is executed, else code script is generated only
@LogUsedThresholdGB int - Max size allowed for loggdb for current database in GB
@maxruntime int - Max runtime in seconds, else run until ready
@disklimit char(4)='0.19' - Disk space limit for disks included in check
@notdisk1 char(1)='C' - Disk not included when checking disk space
@notdisk2 @notdisk3 @notdisk4 see above
@maxdop int - Max degree of parallellism.

A side note you cannot ‘recreate’ an table that contains LOB data types with the database online. One needs to schedule some downtime, take the database offline, and run the stored procedures then. You can reorganize the indexes while the db is online.

· ·

Older posts >>