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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How Does Video Annotation Augment Computer Vision?
  • Role of Data Annotation Services in AI-Powered Manufacturing
  • Annotating Data at Scale in Real Time
  • Filtering Java Collections via Annotation-Driven Introspection

Trending

  • A Guide to Developing Large Language Models Part 1: Pretraining
  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  • Rethinking Recruitment: A Journey Through Hiring Practices
  • While Performing Dependency Selection, I Avoid the Loss Of Sleep From Node.js Libraries' Dangers
  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.3K 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

  • How Does Video Annotation Augment Computer Vision?
  • Role of Data Annotation Services in AI-Powered Manufacturing
  • Annotating Data at Scale in Real Time
  • Filtering Java Collections via Annotation-Driven Introspection

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!