1.@Controller
注解到类名上,表示该类是控制器。
2.@RequestMapping("/xxxx")
可以放在类名/方法名之上,表示访问请求该方法时的url。如果该方法类名有@RequestMapping,则访问该方法的url=项目名+类的RequestMapping+方法的RequestMapping。
3.@Resource
作用相当于@Autowired,只不过@Autowired按类型自动注入,而@Resource默认按byName注入。
@Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。
所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。
如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。
举例:如果Spring上下文中存在不止一个UserDao的bean时,就会抛出BeanCreationException异常;
如果Spring上下文中不存在UserDao类型的bean,也会抛出BeanCreationException异常。
我们可以使用@Qualifier配合@Autowired来解决。
①存在多个bean时,这样解决。
@Autowired
@Qualifier("userServiceImpl")
public IUserService userService;
②不存在时这样解决。
@Autowired(required = false)
public IUserService userService
4.@Service
@Service("Bean的名称") 其中双引号内为可选操作,可以不填,填了代表自定义业务名。整体含义为定义业务层bean。
@Service用在实现类的类名上。如
@Service("alarmManageService")
public class AlarmServiceImp implements AlarmManageService{}
5.@Repository
@Repository("Bean的名称")
定义DAO层Bean
6.@Component
定义Bean, 不好归类时使用。即除了常用的归类外,此Bean不属于其中任何一个,即可用Component修饰。
7.@InitBinder
用于绑定数据,比如前端页面有两个对象,一个student,一个course,切他俩的属性名都一样,此时即可使用该注解。
@Controller
@RequestMapping("/classtest")
public class TestController {
@InitBinder("student")
public void initBinderUser(WebDataBinder binder) {
binder.setFieldDefaultPrefix("student.");
}
@InitBinder("course")
public void initBinderAddr(WebDataBinder binder) {
binder.setFieldDefaultPrefix("course.");
}
@RequestMapping("/methodtest")
@ResponseBody
public Map<String,Object> test(@ModelAttribute("student") Student student,@ModelAttribute("course") Course course){
Map<String,Object> map=new HashMap<String,Object>();
map.put("student", student);
map.put("course", course);
return map;
}