spring-boot注解详解(一)

@SpringBootApplication

@SpringBootApplication = (默认属性)@Configuration + @EnableAutoConfiguration + @ComponentScan。

  1. @Configuration:提到@Configuration就要提到他的搭档@Bean。使用这两个注解就可以创建一个简单的spring配置类,可以用来替代相应的xml配置文件。
<beans> <bean id = "car" class="com.test.Car"> <property name="wheel" ref = "wheel"></property> </bean> <bean id = "wheel" class="com.test.Wheel"></bean>
</beans>

相当于:

@Configuration
public class Conf { @Bean public Car car() { Car car = new Car(); car.setWheel(wheel()); return car; } @Bean  public Wheel wheel() { return new Wheel(); }
}

@Configuration的注解类标识这个类可以使用Spring IoC容器作为bean定义的来源。@Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象应该被注册为在Spring应用程序上下文中的bean。
2、@EnableAutoConfiguration:能够自动配置spring的上下文,试图猜测和配置你想要的bean类,通常会自动根据你的类路径和你的bean定义自动配置。
3、@ComponentScan:会自动扫描指定包下的全部标有@Component的类,并注册成bean,当然包括@Component下的子注解@Service,@Repository,@Controller。

@EnableTransactionManagement

@EnableTransactionManagement 开启事务支持后,然后在访问数据库的Service方法上添加注解 @Transactional 便可。
关于事务管理器,不管是JPA还是JDBC等都实现自接口 PlatformTransactionManager 如果你添加的是 spring-boot-starter-jdbc 依赖,框架会默认注入 DataSourceTransactionManager 实例。如果你添加的是 spring-boot-starter-data-jpa 依赖,框架会默认注入 JpaTransactionManager 实例。
你可以在启动类中添加如下方法,Debug测试,就能知道自动注入的是 PlatformTransactionManager 接口的哪个实现类。


@EnableTransactionManagement // 启注解事务管理,等同于xml配置方式的 <tx:annotation-driven />
@SpringBootApplication
public class ProfiledemoApplication {@Beanpublic Object testBean(PlatformTransactionManager platformTransactionManager){System.out.println(">>>>>>>>>>" + platformTransactionManager.getClass().getName());return new Object();}public static void main(String[] args) {SpringApplication.run(ProfiledemoApplication.class, args);}

这些SpringBoot为我们自动做了,这些对我们并不透明,如果你项目做的比较大,添加的持久化依赖比较多,我们还是会选择人为的指定使用哪个事务管理器。
代码如下:

@EnableTransactionManagement
@SpringBootApplication
public class ProfiledemoApplication {// 其中 dataSource 框架会自动为我们注入@Beanpublic PlatformTransactionManager txManager(DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}@Beanpublic Object testBean(PlatformTransactionManager platformTransactionManager) {System.out.println(">>>>>>>>>>" + platformTransactionManager.getClass().getName());return new Object();}public static void main(String[] args) {SpringApplication.run(ProfiledemoApplication.class, args);}
}

在Spring容器中,我们手工注解@Bean 将被优先加载,框架不会重新实例化其他的 PlatformTransactionManager 实现类。

然后在Service中,被 @Transactional 注解的方法,将支持事务。如果注解在类上,则整个类的所有方法都默认支持事务。

对于同一个工程中存在多个事务管理器要怎么处理,请看下面的实例,具体说明请看代码中的注释。

@EnableTransactionManagement // 开启注解事务管理,等同于xml配置文件中的 <tx:annotation-driven />
@SpringBootApplication
public class ProfiledemoApplication implements TransactionManagementConfigurer {@Resource(name="txManager2")private PlatformTransactionManager txManager2;// 创建事务管理器1@Bean(name = "txManager1")public PlatformTransactionManager txManager(DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}// 创建事务管理器2@Bean(name = "txManager2")public PlatformTransactionManager txManager2(EntityManagerFactory factory) {return new JpaTransactionManager(factory);}// 实现接口 TransactionManagementConfigurer 方法,其返回值代表在拥有多个事务管理器的情况下默认使用的事务管理器@Overridepublic PlatformTransactionManager annotationDrivenTransactionManager() {return txManager2;}public static void main(String[] args) {SpringApplication.run(ProfiledemoApplication.class, args);}}
@Component
public class DevSendMessage implements SendMessage {// 使用value具体指定使用哪个事务管理器@Transactional(value="txManager1")@Overridepublic void send() {System.out.println(">>>>>>>>Dev Send()<<<<<<<<");send2();}// 在存在多个事务管理器的情况下,如果使用value具体指定// 则默认使用方法 annotationDrivenTransactionManager() 返回的事务管理器@Transactionalpublic void send2() {System.out.println(">>>>>>>>Dev Send2()<<<<<<<<");}}

注:
如果Spring容器中存在多个 PlatformTransactionManager 实例,并且没有实现接口 TransactionManagementConfigurer 指定默认值,在我们在方法上使用注解 @Transactional 的时候,就必须要用value指定,如果不指定,则会抛出异常。

对于系统需要提供默认事务管理的情况下,实现接口 TransactionManagementConfigurer 指定。

对有的系统,为了避免不必要的问题,在业务中必须要明确指定 @Transactional 的 value 值的情况下。不建议实现接口 TransactionManagementConfigurer,这样控制台会明确抛出异常,开发人员就不会忘记主动指定。

@Controller

@Controller用于标记在一个类上,使用它标记的类就是一个SpringMvc Controller对象,分发处理器会扫描使用该注解的类的方法,并检测该方法是否使用了@RequestMapping注解。
@Controller只是定义了一个控制器类,而使用@RequestMapping注解的方法才是处理请求的处理器。
@Controller标记在一个类上还不能真正意义上说它就是SpringMvc的控制器,应为这个时候Spring还不认识它,这个时候需要把这个控制器交给Spring来管理。有两种方式可以管理:

<!--基于注解的装配-->
<!--方式一-->
<bean class="com.HelloWorld"/>
<!--方式二-->
<!--路径写到controller的上一层-->
<context:component-scan base-package="com"/>

Action层:

package com;
@Controller
public class HelloWorld{@RequestMapping(value="/showRegUser")public String printHello() {return "hello";}@Autowriedprivate IocSerevce service;public void add(){service.add();}
}

component-scan默认扫描的注解类型是@Component,不过,在@Component的语义基础之上细化为@Reposity,@Service,@Controller.
有一个use-defaultbao’i-filters属性,属性默认是true,表示会扫描抱下所有的标有@Component的类,并注册为bean,也就是@Component的子注解@Service,@reposity等
如果只想扫描包下的@Controller或其他内容,则设置use-default-filters属性为false,表示不再按照scan指定的包进行扫描,而是按照指定包进行扫描

<context:component-scan base-package="com" user-default-filters="false"><context:include-filter type="regex" expression="com.tan.*"/>
</context:component-scan>

当没有设置use-default-filters属性或属性为true时,表示基于base-package包下指定扫描的具体路径。

@RequestMapping

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

RequestMapping注解有六个属性,下面我们把她分成三类进行说明。

1.value, method;

value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);

method: 指定请求的method类型, GET、POST、PUT、DELETE等;
默认 RequestMapping(“url”)即为value的值;
显式说明 RequestMapping(value=”url”)

@Controller
@RequestMapping("/appointments")
public class AppointmentsController {private AppointmentBook appointmentBook;@Autowiredpublic AppointmentsController(AppointmentBook appointmentBook) {this.appointmentBook = appointmentBook;}@RequestMapping(method = RequestMethod.GET)public Map<String, Appointment> get() {return appointmentBook.getAppointmentsForToday();}@RequestMapping(value="/{day}", method = RequestMethod.GET)public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {return appointmentBook.getAppointmentsForDay(day);}@RequestMapping(value="/new", method = RequestMethod.GET)public AppointmentForm getNewForm() {return new AppointmentForm();}@RequestMapping(method = RequestMethod.POST)public String add(@Valid AppointmentForm appointment, BindingResult result) {if (result.hasErrors()) {return "appointments/new";}appointmentBook.addAppointment(appointment);return "redirect:/appointments";}
}

value的url值为以下三类:
A) 可以指定为普通的具体值;

B) 可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);

C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);

example B)@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {Owner owner = ownerService.findOwner(ownerId);  model.addAttribute("owner", owner);  return "displayOwner";
}
example C)@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}")public void handle(@PathVariable String version, @PathVariable String extension) {    // ...}
}

2.consumes,produces;

consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {    // implementation omitted
}
方法仅处理request Content-Type为“application/json”类型的请求。produces的样例:@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {    // implementation omitted
}

方法仅处理request请求中Accept头中包含了”application/json”的请求,同时暗示了返回的内容类型为application/json;

3.params,headers;

params: 指定request中必须包含某些参数值是,才让该方法处理。

headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    // implementation omitted}
}

仅处理请求中包含了名为“myParam”,值为“myValue”的请求;
headers的样例:

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    // implementation omitted}
}

spring-boot注解详解(一)相关推荐

  1. Spring Boot注解详解

    文章目录 使用注解的优势 注解详解(配备了完善的释义) 注解列表如下 JPA注解 springMVC相关注解 全局异常处理 项目中具体配置解析和使用环境 使用注解的优势 采用纯java代码,不在需要配 ...

  2. Spring Boot 单元测试详解+实战教程

    转载自   Spring Boot 单元测试详解+实战教程 Spring Boot 的测试类库 Spring Boot 提供了许多实用工具和注解来帮助测试应用程序,主要包括以下两个模块. spring ...

  3. 《深入理解 Spring Cloud 与微服务构建》第十六章 Spring Boot Security 详解

    <深入理解 Spring Cloud 与微服务构建>第十六章 Spring Boot Security 详解 文章目录 <深入理解 Spring Cloud 与微服务构建>第十 ...

  4. 全面的Spring Boot配置文件详解

    全面的Spring Boot配置文件详解 Spring Boot在工作中是用到的越来越广泛了,简单方便,有了它,效率提高不知道多少倍.Spring Boot配置文件对Spring Boot来说就是入门 ...

  5. Spring Boot 配置文件详解

    2019独角兽企业重金招聘Python工程师标准>>> 第二篇 : Spring Boot配置文件详解 文章首发于微信公众号<程序员果果> 地址:https://mp.w ...

  6. spring boot配置文件详解

    spring boot配置文件详解 application.properties是spring-boot的核心配置文件,这个配置文件基本可以取代我们ssm或者ssh里面的所有的xml配置文件. 当我们 ...

  7. (转) SpringBoot非官方教程 | 第二篇:Spring Boot配置文件详解

    springboot采纳了建立生产就绪spring应用程序的观点. Spring Boot优先于配置的惯例,旨在让您尽快启动和运行.在一般情况下,我们不需要做太多的配置就能够让spring boot正 ...

  8. SpringBoot非官方教程 | 第二篇:Spring Boot配置文件详解

    springboot采纳了建立生产就绪Spring应用程序的观点. Spring Boot优先于配置的惯例,旨在让您尽快启动和运行.在一般情况下,我们不需要做太多的配置就能够让spring boot正 ...

  9. Spring boot——Actuator 详解

    一.什么是 Actuator Spring Boot Actuator 模块提供了生产级别的功能,比如健康检查,审计,指标收集,HTTP 跟踪等,帮助我们监控和管理Spring Boot 应用. 这个 ...

  10. Spring Boot原理详解(一)

    概念: Spring Boot是由Pivotal团队提供的全新框架,属于spring旗下的一个项目,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,它使 ...

最新文章

  1. 12 集成测试方法之大棒集成方法
  2. datagirdview跟据内容自动适应单元格大小
  3. 双绞线,同轴电缆和光纤电缆之间的区别—Vecloud微云
  4. 19、Java并发编程:线程间协作的两种方式:wait、notify、notifyAll和Condition
  5. java画个半径为1地圆_java - 绘制一个半径为圆的圆并围绕边缘指向 - 堆栈内存溢出...
  6. linux7开启ntp服务,【NTP】CentOS7.2配置NTP服务
  7. 图片插值数据_结合PS用这招来增强ArcGIS插值图出图效果
  8. android picasso 三级缓存,Android中图片的三级缓存浅析
  9. iphone屏幕录制_iphone投屏到电脑详细教程
  10. MyBatis的总结(下)
  11. 锁相环环路滤波器计算公式_锁相环PLL的电路原理以及基本构成
  12. Higher level thinking
  13. mysql去掉乱码_mysql消除乱码方法集
  14. WCF中NetTCp配置
  15. win10如何强制性关闭驱动数字签名
  16. php中生成图片代码,用PHP代码在网页上生成图片
  17. Unity 面积测量
  18. Linux 使用Nginx 拦截屏蔽异常访问IP并加入黑名单
  19. java 函数名相同_下列方法不属于java.lang.Math类的有(方法名相同即可)【 】...
  20. 谁偷走了销售人员的时间

热门文章

  1. python34.dll_python34.dll下载
  2. python中np没有定义_python中的np.empty_python – np.empty,np.zeros和np.one
  3. c语言使用未初始化的内存怎么解决_C语言快速入门——数组与调试进阶
  4. php cgi进程很多win2008,php cgi.exe 太多 在 windowserver2008 apache 这个怎么样限制下?...
  5. EM算法(Expectation Maximization Algorithm)
  6. Spring Cloud Sleuth 中id的使用
  7. day2-列表、元组、字典、字符串
  8. 689D Magic Odd Square 奇数幻方
  9. Label 表达式绑定
  10. command line