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 方法来处理。
b.@Service通常与@Transactional一起配合使用。 实现server层的事务整体提交与回滚。
注意:@Transactional的使用具体场景,存在不能回滚的情况,使用时注意。
2.Bean的注入
@Autowired
可注解在set方法上或者属性上,笔者习惯注解在属性上,优点是代码更少、层次更清晰
3.@Configuration 声明此类是一个配置类,通常与注解@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