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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  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

Roger Hughes user avatar by
Roger Hughes
·
Nov. 06, 11 · Interview
Like (1)
Save
Tweet
Share
42.94K 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.

Popular on DZone

  • Comparing Map.of() and New HashMap() in Java
  • The Path From APIs to Containers
  • How To Build a Spring Boot GraalVM Image
  • Unlocking the Power of Elasticsearch: A Comprehensive Guide to Complex Search Use Cases

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: