使用@Resource和@Inject注解自动装配Spring组件
1、Spring还支持使用@Resource和 @Inject给Spring画陲奴颁注册组件。@Resource默认是按照组件名称进行装配的。package com.gwolf.servic髫潋啜缅e;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.gwolf.dao.BookDAO;@Servicepublic class BookService { @Resource private BookDAO bookDAO; public void print() { System.out.println(bookDAO); } }
2、执行junit测试类,查看使用@Resource注入的组件能够注入成功。package com.gwolf.test;import org.junit.Test;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import com.gwolf.config.MainConfigOfAutowired;import com.gwolf.service.BookService;public class ComponentTest { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfAutowired.class); @Test public void testImport() { BookService bookService = (BookService)applicationContext.getBean(BookService.class); bookService.print(); applicationContext.close(); }}
3、如果要想使用@Inject注解,需要导入相关的依赖包。<dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency>
4、在业务层使用@Inject 注入其他的组件。package com.gwolf.service;import javax.annotation.Resource;import javax.inject.Inject;import org.springframework.stereotype.Service;import com.gwolf.dao.BookDAO;@Servicepublic class BookService { @Inject private BookDAO bookDAO; public void print() { System.out.println(bookDAO); } }
5、执行junit测试类,查看使用@Inject注入的组件能够注入成功。
6、@Autowired是spring特有的自动装配注解,@Resource和@Inject是java提供的标准装配注解。