Java Tutorial: How to Use Spring Boot With JSR 330
A senior developer gives a quick tutorial on how to use JSR 330 in a Spring Boot application along with Spring bean annotations. Read on to learn more!
Join the DZone community and get the full member experience.
Join For FreeImplementation
JSR 330 comes with its own set of annotations which are different than Spring annotations. Just using JSR 330 annotations in a Spring environment will not bring in the desired features of JSR 330 – we need to tell the Spring container explicitly to use it and Spring will override its default bean scoping strategy to use JSR 330 scoping. As per the JSR 330 specification, all beans should be of prototype scope by default, unless explicitly marked as a singleton.
We’ll create a simple Spring Boot application with three classes denoted as Spring beans by annotating them with JSR 330 annotations. They will be scanned and added to the Spring context at the application's startup.
Project Structure
Steps
1. Add the javax.inject
Maven dependency into the pom.xml
file.
<dependency>
<groupId>javax.inject</groupId >
<artifactId>javax.inject</arti factId>
<version>1</version>
</dependency>
2. Create an Initializer class by implementing ApplicationContextInitializer
with a type of AnnotationConfigApplicationContext
. The Spring framework comes with a JSR#330 metadata class called Jsr330ScopeMetadataResolver
. We’ll use this class and set the metadata resolver of Spring’s AnnotationConfigApplicationContext
to this class and then tell the context to scan the packages where our components/beans are located explicitly. Lastly, we'll add the initializer with the Spring Application. After that, we'll have a JSR 330 environment inside a Spring container.
See the below image for my code:
TestBean 1
:
TestBean2
with a singleton scope. In a JSR 330 environment, we need to annotate singletons explicitly.
TestBean3
:
Here's what the console will look like after starting the application and checking the registered bean scopes from context:
Opinions expressed by DZone contributors are their own.
Comments