学习Spring Boot第一天之Spring注解式声明和注入Bean
来源:互联网 发布:美国退出qe 知乎 编辑:程序博客网 时间:2024/05/16 15:19
1、声明Bean
@Component 没有明确的角色
@Service 在业务逻辑层(service层)使用
@Repository 在数据访问层使用(dao层)使用
@Controller 在展现层(MVC→Spring MVC)使用
在类名上使用
2、注入Bean
@Autowired:Spring 提供的注解
@Inject:JSR-330提供的注解
@Resource:JSR-250提供的注解
可在属性、set方法上使用
小测试
DAO层:
@Repository
public class TestDAO {
public String SayHello(String word) {
return "Hello " + word + " !";
}
}
Service层:
@Service
public class TestService {
@Autowired
private TestDAO testDAO;
public String SayHello(String word) {
return testDAO.SayHello(word);
}
}
configuration层:
@Configuration
@ComponentScan("com.liang.springboot.dao01.*")
public class TestConfiguration {
}
main层:
public class TestMain {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
TestConfiguration.class);//AnnotationConfigApplicationContext 作为spring的容器,接受输入一个配置类作为参数
// TestService testService = context.getBean(TestService.class);
TestService testService = (TestService) context.getBean("testService");//和类名相同,首字母小写也可以获得Bean
System.out.println(testService.SayHello("小梁"));
context.close();
}
}
使用@configuration声明当前类为配置类
@CompontScan("包名"),讲自动扫描指定包名下有使用@Service、@component、@repository和@controller的类,并注册为Bean。
- 学习Spring Boot第一天之Spring注解式声明和注入Bean
- 声明Spring Bean和注入Bean的几种常用注解和区别
- 【Spring】注解注入bean
- Spring注解注入bean
- Spring Bean自动装配和注解注入
- spring boot Filter 注入bean
- Spring boot 手动注入bean
- Spring(三、Spring Bean自动装配和注解注入)
- spring bean 声明学习
- Spring注解自动注入Bean
- Spring bean 注解方式注入
- spring 使用注解注入bean
- spring注解自动注入bean
- Spring注解自动注入Bean
- Spring Bean装配--@Bean注解注入说明
- Spring学习之声明式事务处理实例(DriverManagerDataSource注入)
- Spring第一天の代码学习(Spring底层依赖注入和控制反转的小例子)
- Spring 注解实现Bean依赖注入之@Required
- MPP 架构数据库
- centos下IntelliJ IDEA运行java项目
- 宿主对象
- Json字符串与Json对象的区别
- Ubuntu常用命令
- 学习Spring Boot第一天之Spring注解式声明和注入Bean
- Git常用命令总结
- 南阳理工acm151Biorhythms(中国剩余定理)
- 机房重构-主窗体
- MTK feature phone 射频参数配置
- 字符串与字符串模板
- 关于Spring的69个面试问答——终极列表
- 子进程的异步等待
- SQLite主键自增