经常使用的spring注解有以下几种:
@Controller
@Service
@Autowired
@RequestMapping
@RequestParam
@ModelAttribute
@Cacheable
@CacheFlush
@Resource
@PostConstruct
@PreDestroy
@Repository
@Component (不推荐使用)
@Scope
@SessionAttributes
@InitBinder
@Required
@Qualifier
@Controller
例如
@Controller
public class SoftCreateController extends SimpleBaseController {}
或者
@Controller("userController")
说明
@Controller 负责注册一个bean 到spring 上下文中,bean 的ID 默认为类名称开头字母小写
@Service
例如
@Service
public class SoftCreateServiceImpl implements ISoftCreateService {}
或者
@Service("softCreateServiceImpl")
说明
@Service 负责注册一个bean 到spring 上下文中,bean 的ID 默认为类名称开头字母小写
@Autowired
例如
@Autowired
private ISoftPMService softPMService;
或者
@Autowired(required=false)
private ISoftPMService softPMService = new SoftPMServiceImpl();
说明
@Autowired 根据bean 类型从spring 上线文中进行查找,注册类型必须惟一,不然报异常。
与@Resource 的区别在于,@Resource 容许经过bean 名称或bean 类型两种方式进行查找@Autowired(required=false) 表示,若是spring 上下文中没有找到该类型的bean 时, 才会使用new SoftPMServiceImpl();
@Autowired 标注做用于 Map 类型时,若是 Map 的 key 为 String 类型,则 Spring 会将容器中全部类型符合 Map 的 value 对应的类型的 Bean 增长进来,用 Bean 的 id 或 name 做为 Map 的 key。
@Autowired 还有一个做用就是,若是将其标注在 BeanFactory 类型、ApplicationContext 类型、ResourceLoader 类型、ApplicationEventPublisher 类型、MessageSource 类型上,那么 Spring 会自动注入这些实现类的实例,不须要额外的操做。
@RequestMapping
类
@Controller
@RequestMapping("/bbtForum.do") 本文来自www.itxxz.com
public class BbtForumController {
@RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(int topicId,User user) {}
}
方法
@RequestMapping("/softpg/downSoftPg.do")
@RequestMapping(value="/softpg/ajaxLoadSoftId.do",method = POST)
@RequestMapping(value = "/osu/product/detail.do", params = { "modify=false" }, method =POST)
说明
@RequestMapping 能够声明到类或方法上
参数绑定说明
若是咱们使用如下的 URL 请求:
http://localhost/itxxzSpring4?method=listBoardTopic&topicId=1&userId=10&userName=tom copyright www.itxxz.com
topicId URL 参数将绑定到 topicId 入参上,而 userId 和 userName URL 参数将绑定到 user 对象的 userId 和 userName 属性中。和 URL 请求中不容许没有 topicId 参数不一样,虽然 User 的 userId 属性的类型是基本数据类型,但若是 URL 中不存在 userId 参数,Spring 也不会报错,此时 user.userId 值为 0 。若是 User 对象拥有一个 dept.deptId 的级联属性,那么它将和 dept.deptId URL 参数绑定。
@RequestParam
参数绑定说明
@RequestParam("id")
http://localhost/itxxzSpring4?method=listBoardTopic&id=1&userId=10&userName=tom
listBoardTopic(@RequestParam("id")int topicId,User user) 中的 topicId 绑定到 id 这个 URL 参数, 那么能够经过对入参使用 @RequestParam 注解来达到目的
@RequestParam(required=false):参数不是必须的,默认为true
@RequestParam(value="id",required=false)
请求处理方法入参的可选类型
Java 基本数据类型和 String
默认状况下将按名称匹配的方式绑定到 URL 参数上,能够经过 @RequestParam 注解改变默认的绑定规则
request/response/session
既能够是 Servlet API 的也能够是 Portlet API 对应的对象,Spring 会将它们绑定到Servlet 和 Portlet 容器的相应对象上
org.springframework.web.context.request.WebRequest
内部包含了 request 对象
java.util.Locale
绑定到 request 对应的 Locale 对象上
java.io.InputStream/java.io.Reader
能够借此访问 request 的内容
java.io.OutputStream / java.io.Writer
能够借此操做 response 的内容
任何标注了 @RequestParam 注解的入参
被标注 @RequestParam 注解的入参将绑定到特定的 request 参数上。
java.util.Map / org.springframework.ui.ModelMap
它绑定 Spring MVC 框架中每一个请求所建立的潜在的模型对象,它们能够被 Web 视图对象访问(如 JSP ) 本文来自www.itxxz.com
命令/ 表单对象(注:通常称绑定使用 HTTP GET 发送的 URL 参数的对象为命令对象,而称绑定使用HTTP POST 发送的 URL 参数的对象为表单对象)
它们的属性将以名称匹配的规则绑定到 URL 参数上,同时完成类型的转换。
而类型转换的规则能够经过 @InitBinder 注解或经过 HandlerAdapter 的配置进行调 整
org.springframework.validation.Errors / org.springframework.validation.BindingResult
为属性列表中的命令/ 表单对象的校验结果,注意检验结果参数必须紧跟在命令/ 表单对象的后面
org.springframework.web.bind.support.SessionStatus
能够经过该类型 status 对象显式结束表单的处理,这至关于触发 session 清除其中的经过@SessionAttributes 定义的属性
请求处理方法返回值的可选类型
void
此时逻辑视图名由请求处理方法对应的 URL 肯定,如如下的方法:
@RequestMapping("/welcome.do")
public void welcomeHandler() {}
对应的逻辑视图名为 “ welcome ”
String
此时逻辑视图名为返回的字符,如如下的方法:
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) {
Owner owner = this.clinic.loadOwner(ownerId);
model.addAttribute(owner);
return "ownerForm";
}
对应的逻辑视图名为 “ ownerForm ”
org.springframework.ui.ModelMap
和返回类型为 void 同样,逻辑视图名取决于对应请求的 URL ,以下面的例子:
@RequestMapping("/vets.do")
public ModelMap vetsHandler() {
return new ModelMap(this.clinic.getVets());
}
对应的逻辑视图名为 “ vets ” ,返回的 ModelMap 将被做为请求对应的模型对象,能够在 JSP 视图页面中访问到。
ModelAndView
固然还能够是传统的 ModelAndView 。
@ModelAttribute
做用域:request
例如
@RequestMapping("/base/userManageCooper/init.do")
public String handleInit(@ModelAttribute("queryBean") ManagedUser sUser,Model model,){
或者
@ModelAttribute("coopMap")// 将coopMap 返回到页 面
public Map<Long,CooperatorInfo> coopMapItems(){}
说明
@ModelAttribute 声明在属性上,表示该属性的value 来源于model 里"queryBean" ,并被保存到model 里@ModelAttribute 声明在方法上,表示该方法的返回值被保存到model 里 itxxz.com
@Cacheable 和@CacheFlush
@Cacheable :声明一个方法的返回值应该被缓 存
例如:@Cacheable(modelId = "testCaching")
@CacheFlush :声明一个方法是清空缓存的触发器
例如:@CacheFlush(modelId = "testCaching")
说明
要配合缓存处理器使用
@Resource
例如
@Resource
private DataSource dataSource; // inject the bean named 'dataSource'
或者
@Resource(name="dataSource")
@Resource(type=DataSource.class)
说明
@Resource 默认按bean 的name 进行查找,若是没有找到会按type 进行查找,
此时与@Autowired 类 似.
在没有为 @Resource 注解显式指定 name 属性的前提下,若是将其标注在 BeanFactory 类型、ApplicationContext 类型、ResourceLoader 类型、ApplicationEventPublisher 类型、MessageSource 类型上,那么 Spring 会自动注入这些实现类的实例,不须要额外的操做。此时 name 属性不须要指定 ( 或者指定为""),不然注入失败;
@PostConstruct 和@PreDestroy
@PostConstruct
在方法上加上注解@PostConstruct ,这个方法就会在Bean 初始化以后被Spring 容器执 行
(注:Bean 初始化包括,实例化Bean ,并装配Bean 的属性(依赖注入))。
@PreDestroy
在方法上加上注解@PreDestroy ,这个方法就会在Bean 被销毁前被Spring 容器执行。
@Repository
与@Controller 、@Service 相似,都是向spring 上下文中注册bean ,不在赘述。
@Component (不推荐使用)
@Component 是全部受Spring 管理组件的通用形式,Spring 还提供了更加细化的注解形式: @Repository 、@Service 、@Controller ,它们分别对应存储层Bean ,业务层Bean ,和展现层Bean 。
目前版本(2.5 )中,这些注解与@Component 的语义是同样的,彻底通用, 在Spring 之后的版本中可能会给它们追加更多的语义。 因此,咱们推荐使用@Repository 、@Service 、@Controller 来替代@Component 。
@Scope
例如
@Scope("session")
@Repository()
public class UserSessionBean implementsSerializable {}
说明
在使用XML 定义Bean 时,能够经过bean 的scope 属性来定义一个Bean 的做用范围,
一样能够经过@Scope 注解来完成
@Scope中能够指定以下值:
singleton:定义bean的范围为每一个spring容器一个实例(默认值)
prototype:定义bean能够被屡次实例化(使用一次就建立一次)
request:定义bean的范围是http请求(springMVC中有效)
session:定义bean的范围是http会话(springMVC中有效)
global-session:定义bean的范围是全局http会话(portlet中有效)
@SessionAttributes
说明
Spring 容许咱们有选择地指定 ModelMap 中的哪些属性须要转存到 session 中,
以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。
这一功能是经过类定义处标注 @SessionAttributes 注解来实现的。
@SessionAttributes 只能声明在类上,而不能声明在方法上。
例如
@SessionAttributes("currUser") // 将ModelMap 中属性名为currUser 的属性
@SessionAttributes({"attr1","attr2"})
@SessionAttributes(types = User.class)
@SessionAttributes(types = {User.class,Dept.class})
@SessionAttributes(types = {User.class,Dept.class},value={"attr1","attr2"})
@InitBinder
说明
若是但愿某个属性编辑器仅做用于特定的 Controller ,
能够在 Controller 中定义一个标注 @InitBinder 注解的方法,
能够在该方法中向 Controller 了注册若干个属性编辑器
例如
@InitBinder
public void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
@Required
例如
@required
public setName(String name){}
说明 copyright www.itxxz.com
@ required 负责检查一个bean在初始化时其声明的 set方法是否被执行, 当某个被标注了 @Required 的 Setter 方法没有被调用,则 Spring 在解析的时候会抛出异常,以提醒开发者对相应属性进行设置。 @Required 注解只能标注在 Setter 方法之上。由于依赖注入的本质是检查 Setter 方法是否被调用了,而不是真的去检查属性是否赋值了以及赋了什么样的值。若是将该注解标注在非 setXxxx() 类型的方法则被忽略。
@Qualifier
例如
@Autowired
@Qualifier("softService")
private ISoftPMService softPMService;
说明
使用@Autowired 时,若是找到多个同一类型的bean,则会抛异常,此时可使用 @Qualifier("beanName"),明确指定bean的名称进行注入,此时与 @Resource指定name属性做用相同。
html
注解注入java
注解注入顾名思义就是经过注解来实现注入,Spring和注入相关的常见注解有Autowired、Resource、Qualifier、Service、Controller、Repository、Component。mysql
Autowired是自动注入,自动从spring的上下文找到合适的bean来注入web
Resource用来指定名称注入ajax
Qualifier和Autowired配合使用,指定bean的名称spring
Service,Controller,Repository分别标记类是Service层类,Controller层类,数据存储层的类,spring扫描注解配置时,会标记这些类要生成bean。sql
Component是一种泛指,标记类是组件,spring扫描注解配置时,会标记这些类要生成bean。缓存
上面的Autowired和Resource是用来修饰字段,构造函数,或者设置方法,并作注入的。而Service,Controller,Repository,Component则是用来修饰类,标记这些类要生成bean。session
下面咱们经过实例项目来看下spring注解注入的使用。app
首先新建一个maven项目,并在pom中添加spring相关的依赖,若是不知道添加那些依赖,请参照上一篇文章。
而后新建CarDao类,给它添加@Repository注解,以下代码:
package cn.outofmemory.helloannotation;import org.springframework.stereotype.Repository;@Repositorypublic class CarDao { public void insertCar(String car) { String insertMsg = String.format("inserting car %s", car); System.out.println(insertMsg); }}
新建CarService类,并给该类标注@Service注解,在这个类中定义CarDao的字段,并经过Autowired来修饰此字段,这样上面定义的CarDao类的实例就会自动注入到CarService的实例中了。
package cn.outofmemory.helloannotation;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class CarService { @Autowired private CarDao carDao; public void addCar(String car) { this.carDao.insertCar(car); }}
注意:Autowired注解有一个能够为空的属性required,能够用来指定字段是不是必须的,若是是必需的,则在找不到合适的实例注入时会抛出异常。
下面咱们在App.java中使用上面测试下注解注入:
package cn.outofmemory.helloannotation;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;/** * Hello world! * */public class App { public static void main( String[] args ) { ApplicationContext appContext = new AnnotationConfigApplicationContext("cn.outofmemory.helloannotation"); CarService service = appContext.getBean(CarService.class); service.addCar("宝马"); }}
在上面的main方法中首先咱们初始化了appContext,他是AnnotationConfigApplicationContext,它的构造函数接受一个package的名称,来限定要扫描的package。而后就能够经过appContext的getBean方法得到CarService的实例了。
上面的例子很是简单,单纯的使用AnnotationConfigApplicationContext就能够了,可是在实际项目中状况每每没有这么简单,仍是须要spring配置文件的。在spring配置文件中也能够经过下面的配置让spring自动扫描注解配置。
<!-- bean annotation driven --> <context:annotation-config /> <context:component-scan base-package="cn.outofmemory.helloannotation" > </context:component-scan>
下面咱们看下混合使用spring配置和注解的例子,首先在项目中添加source folder,src/main/resources,并添加spring.xml, 其内容以下:
<?xml version="1.0" encoding="utf-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!-- bean annotation driven --> <context:annotation-config /> <context:component-scan base-package="cn.outofmemory.helloannotation" > </context:component-scan> <bean id="sqliteCarDao" class="cn.outofmemory.helloannotation.CarDao" > <constructor-arg name="driver" value="sqlite"/> </bean> </beans>
在上面的配置文件中,咱们经过context:annotation-config和context:component-sacn节点来指定要扫描注解注入,而后又定义了一个id为sqliteCarDao的bean,它的构造函数的driver值为sqlite。
咱们修改下App.java使用xml配置文件,再运行下App看下会怎样。
package cn.outofmemory.helloannotation;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * Hello world! * */public class App { public static void main( String[] args ) { //ApplicationContext appContext = new AnnotationConfigApplicationContext("cn.outofmemory.helloannotation"); ApplicationContext appContext = new ClassPathXmlApplicationContext("/spring.xml"); CarService service = appContext.getBean(CarService.class); service.addCar("宝马"); }}
运行程序发现输出为:inserting car 宝马 into mysql
,显然CarService自动注入的CarDao使用了默认构造函数构造的实例。是否能够经过注解指定使用spring.xml中配置的sqliteCarDao呢?
咱们能够修改下CarService类,经过Qualifier注解来指定要使用的bean的名字。
以下,在指定Autowired注解时,同时指定Qualifier注解指定bean的名字
@Autowired @Qualifier("sqliteCarDao") private CarDao carDao;
从新运行下App.java 此次输出的是inserting car 宝马 into sqlite
,此次使用了spring.xml中配置的bean了。
在文中开头咱们还提到了Resouce注解,这个注解能够指定名字注入,咱们再次修改下CarService类:
@Resource(name="sqliteCarDao") private CarDao carDao;
javax.annotation.Resource注解实现的效果和@Autowired+@Qualifier的效果是同样的。