DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Quality Crisis in Robotics and How Video Annotation Fixes It
  • Active Learning and Human-in-the-Loop for NLP Annotation and Model Improvement
  • How Does Video Annotation Augment Computer Vision?

Trending

  • Reducing RAG Hallucinations With Relationship-Aware Retrieval
  • Cutting Data Pipeline Costs and Data Freshness Issues With Netflix Maestro and Apache Iceberg: A Practical Tutorial
  • The Latency Tax That’s Hidden in Cloud-Native Systems (and the Hard Lessons I Learned to Minimize It)
  • How to Set MX Records via API: Automate Email Routing Programmatically
  1. DZone
  2. Coding
  3. Languages
  4. Using JSR-250's @PostConstruct Annotation to Replace Spring's InitializingBean

Using JSR-250's @PostConstruct Annotation to Replace Spring's InitializingBean

By 
Roger Hughes user avatar
Roger Hughes
·
Nov. 06, 11 · Interview
Likes (1)
Comment
Save
Tweet
Share
44.8K Views

Join the DZone community and get the full member experience.

Join For Free

JSR-250 aka Common Annotations for the Java Platform was introduced as part of Java EE 5 an is usually used to annotated EJB3s. What’s not so well known is that Spring has supported three of the annotations since version 2.5. The annotations supported are:

  • @PostContruct - This annotation is applied to a method to indicate that it should be invoked after all dependency injection is complete.
  • @PreDestroy - This is applied to a method to indicate that it should be invoked before the bean is removed from the Spring context, i.e. just before it’s destroyed.
  • @Resource - This duplicates the functionality of @Autowired combined with @Qualifier as you get the additional benefit of being able to name which bean you’re injecting, without the need for two annotations.

This blog takes a quick look at the first annotation in the list @PostConstruct, demonstrating how it’s applied and comparing it to the equivalent InitializingBean interface.

InitializingBean has one method, afterPropertiesSet(), and it does what it says on the tin. The afterPropertiesSet() method is called after Spring has completed wiring things together. The code snippet below demonstrates how InitializingBean is implemented.
public class ImplementInitializingBean implements InitializingBean {

  private boolean result;

  public String businessMethod() {

    System.out.println("Inside - ImplementInitializingBean");
    return "InitializingBeanResult";
  }

  /**
   * This is part of the InitializingBean interface - called after the bean has been set-up. Use this method to check that the
   * bean has been set-up correctly. Also so use it to configure external resources such as databases etc.
   */
  @Override
  public void afterPropertiesSet() throws Exception {

    result = true;
    System.out.println("In aferPropertiesSet() - check the set-up of the bean.");
  }

  public boolean getResult() {
    return result;
  }
}

Annotations are supposed to make life easier, but do they in this case? Firstly to use the @PostConstruct annotation you need to include the following dependencies your POM file:

<!-- Required for Spring annotations -->          
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>

You also need to tell Spring to use annotations by adding the following to your Spring config file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="jsr250annotations" />

    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />
</beans>

Having setup the environment, you can now use the @PostConstruct annotation.
@Component
public class ImplementPostConstruct implements MyPostConstructExample {

  private boolean result;

  @Override
  public String businessMethod() {

    System.out.println("Inside - ImplementPostConstruct");
    return "ImplementPostConstruct";
  }

  /**
   * @PostConstruct means that this is called after the bean has been set-up.
   *                Use this method to check that the bean has been set-up
   *                correctly. Also so use it to configure external resources
   *                such as databases etc.
   */
  @PostConstruct
  public void postConstruct() {

    result = true;
    System.out
        .println("In postConstruct() - check the set-up of the bean.");
  }

  @Override
  public boolean getResult() {
    return result;
  }
}

This is tested using the JUnit Test below:
  @Test
  public void postConstructTest() {

    instance1 = ctx.getBean(ImplementPostConstruct.class);

    String result = instance1.businessMethod();
    assertEquals("ImplementPostConstruct", result);

    boolean var = instance1.getResult();
    assertTrue(var);
  }

The two clumps of code above do the same thing with postConstruct() being called at the same time asafterPropertiesSet(). It's easy to see that annotations look neater, but they are also more difficult to setup? I'll let you be the judge of that. Finally, one last thing to note, the JSR-250 annotations provide useful core functionality, but are part of Spring's MVC project warranting a possible superfluous dependency on the javax.servlet-api jar, so perhaps a little refactoring may be a good idea at some point.

 

From http://www.captaindebug.com/2011/11/using-jsr-250s-postconstruct-annotation.html

Annotation JSR 250

Opinions expressed by DZone contributors are their own.

Related

  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Quality Crisis in Robotics and How Video Annotation Fixes It
  • Active Learning and Human-in-the-Loop for NLP Annotation and Model Improvement
  • How Does Video Annotation Augment Computer Vision?

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook