SpringBoot之依赖注入DI

相关注解:

@Component

  @Service

  @Controller

  @Repository

---------------------------------------------

@Inject:JSr-330提供的注解

@Autowire:Spring提供的注解

@Resource:JSR-250提供的注解

三者可以注解在set方法上,也可以注解在属性上,习惯性注解在属性上。

-----------------------------------------------------------------

eg:

使用@Service注解声明当前类似spring管理的一个Bean。

 1 package com.wisely.heighlight_spring4.ch1.di;
 2 
 3 import org.springframework.stereotype.Service;
 4 
 5 @Service
 6 public class FunctionService {
 7     public String sayHello(String world) {
 8         return "Hello" + world;
 9     }
10 }

1、声明当前类似spring管理的一个Bean。

2、@Autowire将FunctionService实体类注入UseFunctionService中

 1 package com.wisely.heighlight_spring4.ch1.di;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.stereotype.Service;
 5 
 6 @Service
 7 public class UseFunctionService {
 8     
 9     @Autowired
10     private FunctionService functionService;
11 
12     public String sayHello(String world) {
13         return functionService.sayHello(world);
14     }
15 }

1、@Configuration注解当前类是一个配置类

2、@ComponentScan注解扫描当前包下所有包含@Component、@Service、@Controller、@Repository的类,并注册为Bean。

 1 package com.wisely.heighlight_spring4.ch1.di;
 2 
 3 import org.springframework.context.annotation.ComponentScan;
 4 import org.springframework.context.annotation.Configuration;
 5 
 6 /**
 7  * 
 8  * @Configuration 当前类是配置类
 9  * @ComponentScan 自动扫描报名下所有使用 @component @service @controller @repository 的类,
10  *                   并注册为Bean
11  * 
12  */
13 @Configuration
14 @ComponentScan("com.wisely.heighlight_spring4.ch1.di")
15 public class DiConfig {
16 
17 }

 

posted @ 2018-03-22 09:44  JohnEricCheng  阅读(1628)  评论(0编辑  收藏  举报