Types of Spring DI related annotations
Context Configuration Annotations @Scope @Autowired @Resource @Inject @Required @Named @Order @PostConstruct @PreDestroy
@Scope
Generally, only one bean that automatically scans with @Component @Service @Repository is generated as a singleton, but you can use the @Scope annotation to change this. In other words, I will set the range of beans.
singleton-Return one bean per ʻIoC container
prototype --Creates a new bean every time there is a
requestand returns request-returns one bean per
HTTP request objectsession-returns one bean per
HTTP session objectglobalSession-Returns one bean for
all sessions`
Example
@Component
@Scope("prototype")
Class Hoge { ... }
<bean id="hoge" class="aaa.java.bbb.ccc.hoge" scope="prototype" />
If you have Bean injected, you can use the following annotations.
@Autowired
Annotations belonging to Spring Framework
Applies if the bean id or name matches. Type Driven Injection
If some beans are searched, they are distinguished by the @Qualifier (name =" hoge ")
annotation.
Beans are basically injected for all attributes that are @Autowired.
--Applicable places: member variables, setter methods, constructs, general methods
@Resource
Annotations that can be used in Spring 2.5 and above and do not belong to the Spring Framework
Find the bean that is injected by bean name. To use it, add jsr250-api.jar
from the JSR.250 library to your classpath.
--Applicable places: member variables, setter methods
Maven settings
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
@Inject
It can be used with Spring 3.0 or higher. It is recommended to use @Inject to configure apps that do not belong to a particular framework. To use it, add javax.inject-x.x.x.jar
from the JSR.330 library to your classpath.
--Applicable places: member variables, setter methods, constructs, general methods
Maven settings
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
@Required
It is used to write on the Setter method and set required properties. To use it, you can register the RequiredannotationBeanPostProcessor class as a bean or add the <context.annotation-config> setting.
Example
package day1;
public class Emp {
private String ename;
@Requried
public void setEname( String ename ) { this.ename = ename; }
public String getName() { return this.ename; }
}
Beans.xml
<bean id="emp" class="day1.Emp" >
<!--Error if the following properties are not set-->
<!-- <property ename="ename" value="hoge" /> -->
</bean>
main()
ApplicationContext ctx = new ClassPathXmlApplicationContext("Beans.xml");
Emp emp = (Student) ctx.getBean("emp");
System.out.println("Ename : " + emp.getEname());
When I run it, I get the following error:
>
#### **`Error`**
```ruby
Property 'ename' is required for bean 'emp'
I'm a little tired@Named @Order @About PostConstruct tomorrow ...
Recommended Posts