以下一切都是基于《Java EE开发的颠覆者 Spring Boot 实战》一书
依赖注入的定义
在Spring中控制反转(Inversion of Control - IOC)和依赖注入(dependency injection-DI)是同等概念,控制反转是通过依赖注入实现的。所谓依赖注入指的是容器负责创建对象和维护对象间的依赖关系,而不是通过对象本身负责自己的创建和解决自己的依赖。
Spring IoC容器负责创建Bean,并通过容器将功能类Bean注入到你需要的Bean中。Spring提供使用xml、注解、Java配置、groovy配置实现Bean的创建和注入。
声明Bean的注解:
@Component组件,没有明确的角色
@Service在业务层Service层使用
@Repository在数据访问层Dao层使用
@Controller在展现层使用
注入Bean的注解:
@Autowired:Spring提供的注解
@Inject:JSR-330提供的注解
@Resource:JSR-250提供的注解
示例
1.编写功能类的Bean
@Service
public class FunctionService {
public String sayHello(String word){
return "Hello "+word+" !";
}
}
@Service声明当前FunctionService类是Spring管理的一个Bean。
注:@Component、@Service、@Repository和@Contoller是等效的,根据不同的业务层进行使用。
2.使用功能类的Bean
@Service
public class UseFunctionService {
@Autowired
FunctionService functionService;
public String SayHello(String word){
return functionService.sayHello(word);
}
}
同样用@Service进行Bean的声明,同时使用@Autowired将FunctionService的实体Bean注入到UseFunctionService中,@Inject和@Resource注解也是等效的
3.配置类,因为是简单的例子所以直接使用配置类
@Configuration
@ComponentScan("service")
public class DiConfig {
}
@Configuration注解声明当前类是一个配置类,@ComponentScan表示扫描service包下所有的使用@Service、@Componetn、@Repository、和@Controller的类,并注册成Bean。
4.运行
@Test
public void test(){
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(DiConfig.class);
UseFunctionService useFunctionService=context.getBean(UseFunctionService.class);
System.out.println(useFunctionService.SayHello("di"));
context.close();
}
通过读取配置类,生产Spring容器,通过Spring创建bean,并且使用创建的bean。