
正文
SpringBoot之依赖注入DI
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
相关注解:
@Component
@Service
@Controller
@Repository
---------------------------------------------
@Inject:JSr-330提供的注解
@Autowire:Spring提供的注解
@Resource:JSR-250提供的注解
三者可以注解在set方法上,也可以注解在属性上,习惯性注解在属性上。
-----------------------------------------------------------------
eg:
使用@Service注解声明当前类似spring管理的一个Bean。
package com.wisely.heighlight_spring4.ch1.di; import org.springframework.stereotype.Service; @Service
public class FunctionService {
public String sayHello(String world) {
return "Hello" + world;
}
}
1、声明当前类似spring管理的一个Bean。
2、@Autowire将FunctionService实体类注入UseFunctionService中
package com.wisely.heighlight_spring4.ch1.di; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class UseFunctionService { @Autowired
private FunctionService functionService; public String sayHello(String world) {
return functionService.sayHello(world);
}
}
1、@Configuration注解当前类是一个配置类
2、@ComponentScan注解扫描当前包下所有包含@Component、@Service、@Controller、@Repository的类,并注册为Bean。
package com.wisely.heighlight_spring4.ch1.di; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; /**
*
* @Configuration 当前类是配置类
* @ComponentScan 自动扫描报名下所有使用 @component @service @controller @repository 的类,
* 并注册为Bean
*
*/
@Configuration
@ComponentScan("com.wisely.heighlight_spring4.ch1.di")
public class DiConfig { }







