spring 学习最重要的就是注解吧...
1.Bean 的声明
@Component 组件, 没有明确的角色.
@Service 在业务逻辑层 (service 层) 使用.
@Repository 在数据访问层 (dao 层) 使用.
@Controller 在展现层 (MVC→Spring MVC) 使用.
特别说明:
a. 在声明普通 Bean 的时候, 使用 @Component,@Service,@Repository 和 @Controller 是等同的, 因为 @Service,@Repository,@Controller 都组合了 @Compoment 元注解;
但在 Spring MVC 声明控制器 Bean 的时候, 只能使用 @Controller.
@Controller 将其声明为 Spring 的一个 Bean, 并将 web 请求映射到注解了 @RequestMapping 的方法上
例子:
- @Control ler
- @RequestMapping ( "/test")
- public class HelloworldController {
- @RequestMapping ( "/index.html" )
- public String say (Model model) {
- model.addAttribute ( "name","hello,world" ) ;
- return "/index.btl";
- }
- }
如以上代码所示,@Controller 作用于类上, 表示这是一个 MVC 中的 Controller .
@RequestMapping 既可以作用在方法上, 也可以作用在类上. 如上例所示, 用户如果访问 / test/index.HTML , 则会交给 HelloworldController.say 方法来处理.
[email protected]通常与@Transactional 一起配合使用. 实现 server 层的事务整体提交与回滚.
注意:@Transactional 的使用具体场景, 存在不能回滚的情况, 使用时注意.
2.Bean 的注入
@Autowired
可注解在 set 方法上或者属性上, 笔者习惯注解在属性上, 优点是代码更少, 层次更清晰
[email protected] 声明此类是一个配置类, 通常与注解@Bean 共用
@Configuration 标注在类上, 相当于把该类作为 spring 的 xml 配置文件中的 < beans>
@Configuation 等价于 < Beans></Beans>
@Bean 等价于 < Bean></Bean>
@ComponentScan 等价于 < context:component-scan base-package="com.dxz.demo"/>
既然 @Bean 的作用是声明 bean 对象, 那么完全可以使用 @Component,@Controller,@Service,@Ripository 等注解声明 bean, 当然需要配置 @ComponentScan 注解进行自动扫描
4. 常用注解说明
@RestController 相当于@Controller 和@ ResponseBody
SpringBoot 学习(二): 注解
来源: http://www.bubuko.com/infodetail-3277455.html