dineshonjava

JSR 330 Annotations in Spring

JSR 330 Annotations in Spring

Spring provides support for JSR 330 annotations since Spring 3.0. As spring annotations JSR 330 annotations are also working in the spring bean container. You just need to have the relevant jars in your classpath.

In pom.xml file add
<dependency>
    <groupId>javax.inject</groupId>
    <artifactId>javax.inject</artifactId>
    <version>1</version>
</dependency>

JSR-330 standard annotations (Dependency Injection):

  • Also known as @Inject
  • Joint JCP effort bu Google and SpringSource
  • Standardizes internal DI annotations
  • Published late 2009
Dependency Injection with @Inject and @Named
Instead of @Autowired, @javax.inject.Inject may be used as follows:
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class TransferServiceImpl implements TransferService{

    @Inject
    public void TransferServiceImpl(@Named("accountRepository") AccountRepository accountRepository ) {
        this.accountRepository = accountRepository ;
    }

 }


import javax.inject.Named;

@Named("accountRepository")
public class JdbcAccountRepository implements AccountRepository {
//...
}


  • As with @Autowired, it is possible to use @Inject at the field level, method level and constructor-argument level.
  • As with @Component, it is possible to use @Named at the class level for component scanning by @ComponentScan
  • If you would like to use a qualified name for the dependency that should be injected, you should use the @Named annotation as with @Qualifier.

Note: In contrast to @Component, the JSR-330 @Named annotation are not composable. Please use Spring’s stereotype model for building custom component annotations.

From @Autowired to @Inject
Spring JSR 330 Comments
@Autowired
@Inject
@Inject always mandatory, has no 'required' attribute.
@Component
@Named
Spring also scan for @Named .
@Scope @Scope JSR 330 Scope for ,eta annotation and injection point only
@Scope("singleton")
@Singleton
JSR-330 default scope is like Spring’s prototype.
@Qualifier
@Named
@Value
No equivalent SpEL specific
@Required
Redundant @Inject always required
@Lazy
No equivalent Useful when needed, often abused