文章目录
- @SpringBootApplication
- @Enable*
- @Table
- @Basic
- @Column
- @id
- @Scope
- @Configuration
- @Bean
- token相关注解:
- @Qualifier
- @Autowired
- @Component
- @Service
- @Controller
- @Repository
- @RestController
- @ResponseBody
- @RequestParam
- @RequestBody
- @GetMapping
- @PostMapping
- @PutMapping
- @DeleteMapping
- @Select
- @MapperScan
- @Data
- @NoArgsConstructor
- @AllArgsConstructor
- @Param
- @Resource
- @ControllerAdvice
- @ExceptionHandler
- @ResponseStatus
- AOP注解:
- @ComponentScan
- @Primary
- @PostConstruct
- @PreDestory
- @EnableWebSocket
- @ServerEndpoint
- @KafkaListener
- Cloud注解
@SpringBootApplication
是Sprnig Boot项目的核心注解,目的是开启自动配置
实现了以下三个注解的功能:
@EnableAutoConfiguration:启用Spring Boot的自动配置机制
@ComponentScan:启用@Component对应用程序所在的软件包的扫描
@Configuration:允许在上下文中注册额外的bean或导入其他配置类
@Enable*
启用什么什么服务,里面会import导入配置类
@Table
spring @Table注解 作用是 : 声明此对象映射到数据库的数据表,通过它可以为实体指定表(talbe)
常用的两个属性:
1、name 用来命名 当前实体类 对应的数据库 表的名字
@Table(name = "tab_user")
2、uniqueConstraints 用来批量命名唯一键
其作用等同于多个:@Column(unique = true)
@Table(name = "tab_user",uniqueConstraints = {@UniqueConstraint(columnNames={"uid","email"})})
@Basic
@Basic表示一个简单的属性到数据库表的字段的映射,对于没有任何标注的getXxxx()方法,默认 即为
@Basic
(1)、FetchType.LAZY:懒加载,加载一个实体时,定义懒加载的属性不会马上从数据库中加载。
(2)、FetchType.EAGER:急加载,加载一个实体时,定义急加载的属性会立即从数据库中加载。
示例:
@Basic(fetch=FetchType,optional=true)
public String getAddress() { return address; }
@Column
@Column描述了数据库表中该字段的详细定义,这对于根据JPA注解生成数据库表结构的工具非常 有作用.
@Column:
name:表示数据库表中该字段的名称,默认情形属性名称一致
nullable:表示该字段是否允许为null,默认为true
unique:表示该字段是否是唯一标识,默认为false
length:表示该字段的大小,仅对String类型的字段有效
insertable:表示在ORM框架执行插入操作时,该字段是否应出现INSETRT语句中,默认为true
updateable:表示在ORM框架执行更新操作时,该字段是否应该出现在UPDATE语句中,默认为 true.对于一经创建就不可以更改的字段,该属性非常有用,如对于birthday字段.
columnDefinition:表示该字段在数据库中的实际类型.通常ORM框架可以根据属性类型自动判 断数据库中字段的类型,但是对于Date类型仍无法确定数据库中字段类型究竟是DATE,TIME还是 TIMESTAMP.此外,String的默认映射类型为VARCHAR,如果要将String类型映射到特定数据库的 BLOB或TEXT字段类型,该属性非常有用.
示例:
@Column(name="BIRTH",nullable="false",columnDefinition="DATE")
public String getBithday() { return birthday; }
@id
@Id 标注用于声明一个实体类的属性映射为数据库的主键列。
该属性通常置于属性声明语句之前,可与声明语句同行,也可写在单独行上。
@Id标注也可置于属性的getter方法之前。
示例:
@Table(name="admin")
public class Customer {
@Id
private Integer id;
private String name;
private String email;
private int age;
@Basic
@Column(name="id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Scope
用于指定scope作用域的(用在类上)
@Configuration
@Configuration推荐文章连接
从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。
示例:
@Configuration
public class TestConfiguration {
public TestConfiguration() {
System.out.println("TestConfiguration容器启动初始化。。。");
}
}
@Configuration
public class TestConfiguration {
public TestConfiguration() {
System.out.println("TestConfiguration容器启动初始化。。。");
}
// @Bean注解注册bean,同时可以指定初始化和销毁方法
// @Bean(name="testBean",initMethod="start",destroyMethod="cleanUp")
@Bean
@Scope("prototype")
public TestBean testBean() {
return new TestBean();
}
}
@Bean
Spring的@Bean注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。产生这个Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中。
@Bean:
value: name属性的别名,在不需要其他属性时使用,也就是说value 就是默认值
name: 此bean 的名称,或多个名称,主要的bean的名称加别名。如果未指定,则bean的名称是带注解方法的名称。如果指定了,方法的名称就会忽略,如果没有其他属性声明的话,bean的名称和别名可能通过value属性配置
initMethod :指定初始化方法
destroyMethod:指定销毁的方法 PS:相当于xml文件中 init-method &destroy-method属性
token相关注解:
下面两个注解是token的请求相关的,官网文档地址:
https://docs.spring.io/spring-security-oauth2-boot/docs/2.2.0.RELEASE/reference/html5/
@EnableAuthorizationServer
启用授权服务器,默认情况下,@EnableAuthorizationServer授予客户端访问客户端凭据的权限
与其他Spring Boot@Enable注释类似,可以将@EnableAuthorizationServer注释添加到main方法的类中
示例:
@EnableAuthorizationServer
@SpringBootApplication
public class SimpleAuthorizationServerApplication {
public static void main(String[] args) {
SpringApplication.run(SimpleAuthorizationServerApplication, args);
}
}
@EnableResourceServer
指定用于验证承载令牌的策略,添加此注释会添加OAuth2AuthenticationProcessingFilter,尽管它还需要进行其他配置才能知道如何适当地处理和验证令牌。
与其他Spring Boot@Enable注释类似,可以将@EnableResourceServer注释添加到main方法的类中
示例:
@EnableResourceServer
@SpringBootApplication
public class SimpleAuthorizationServerApplication {
public static void main(String[] args) {
SpringApplication.run(SimpleAuthorizationServerApplication, args);
}
}
@EnableWebSecurity
参考文章:https://blog.youkuaiyun.com/andy_zhang2007/article/details/90023901
首先,EnableWebSecurity注解是个组合注解,他的注解中,又使用了@EnableGlobalAuthentication注解:
@EnableWebSecurity是Spring Security用于启用Web安全的注解。典型的用法是该注解用在某个Web安全配置类上(实现了接口WebSecurityConfigurer或者继承自WebSecurityConfigurerAdapter)。典型的使用例子如下 :
示例:
@Configuration
@EnableWebSecurity
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
// Spring Security should completely ignore URLs starting with /resources/
.antMatchers("/resources/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/public/**").permitAll().anyRequest()
.hasRole("USER").and()
// Possibly more configuration ...
.formLogin() // enable form based log in
// set permitAll for all URLs associated with Form Login
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
// enable in memory based authentication with a user named "user" and "admin"
.inMemoryAuthentication().withUser("user").password("password").roles("USER")
.and().withUser("admin").password("password").roles("USER", "ADMIN");
}
// Possibly more overridden methods ...
}
@Qualifier
使用@Qualifier明确指定使用那个实现类了。
@Autowired
@Autowired 注释,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作
它是按照类型来自动进行标注
示例:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void save(){
userRepository.save();
}
}
@Component
实现bean的注入
针对不同的使用场景所采取的特定功能化的注解。
@Service
一般使用@Service注解标记这个类属于业务逻辑层。
就是针对不同的使用场景所采取的特定功能化的注解。
@Controller
这个注解主要告诉Spring这个类作为控制器,可以看做标记为暴露给前端的入口。@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法。通俗来说,被Controller标记的类就是一个控制器,这个类中的方法,就是相应的动作。
就是针对不同的使用场景所采取的特定功能化的注解。
@Repository
这个注解用来标识这个类是用来直接访问数据库的,dao层使用@repository注解。
@RestController
@Controller+@ResponseBody
@ResponseBody
@ResponseBody的作用其实是将java对象转为json格式的数据。
@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据。
@RequestParam
注解@RequestParam接收的参数是来自HTTP请求体或请求url的QueryString中。
@RequestParam有三个配置参数:
required 表示是否必须,默认为 true,必须。
defaultValue 可设置请求参数的默认值。
value 为接收url的参数名(相当于key值)。
@RequestParam用来处理 Content-Type 为 application/x-www-form-urlencoded 编码的内容,Content-Type默认为该属性。@RequestParam也可用于其它类型的请求,例如:POST、DELETE等请求。
@RequestBody
注解@RequestBody接收的参数是来自requestBody中,即请求体。一般用于处理非 Content-Type: application/x-www-form-urlencoded编码格式的数据,比如:application/json、application/xml等类型的数据。
通俗的讲,就是会把你传入的json字符解析成该参数类型的Javabean对象。
GET 方式无请求体,所以 @RequestBody 接收数据时,前端必须是 POST 方式进行提交,然后给页面的数据默认也是 json
同一个方法中,@RequestBody 与 @RequestParam() 可以同时使用,前者最多只能有一个,后者可以有多个
@GetMapping
@GetMapping 注解将 HTTP GET 请求映射到特定的处理程序方法。
@PostMapping
@GetMapping 注解将 HTTP POST 请求映射到特定的处理程序方法。
@PutMapping
@GetMapping 注解将 HTTP PUT 请求映射到特定的处理程序方法。
@DeleteMapping
@GetMapping 注解将 HTTP Delete 请求映射到特定的处理程序方法。
@Select
在Mapper层使用@Select注解,以此省略掉mapper.xml文件
示例:
@Select("<script>"
+"select * from mi_taobao where 1=1"
+"<if test='status != null'>"
+"and status = #{status}"
+"</if>"
+"</script>")
public List<Taobao> getTaobao(@Param("status") Integer status);
@Select({ "SELECT "
+ " a.id, "
+ " a.role_name roleName, "
+ " a.enabled, "
+ " a.create_by createBy, "
+ " a.create_time createTime "
+ " FROM "
+ " sys_role a "
+ " WHERE "
+ " a.id = #{roleId}" })
SysRole selectSysRoleById(Long roleId);
@MapperScan
指定要变成实现类的接口所在的包,然后包下面的所有接口在编译之后都会生成相应的实现类
在Springboot启动类上面添加
示例:
@SpringBootApplication
//@EnableEurekaClient
@MapperScan("com.winter.dao")
public class SpringbootMybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
}
}
多个包扫描:
@SpringBootApplication
@MapperScan({"com.kfit.demo","com.kfit.user"})
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
@Data
作用在实体类上,生成对应的getset方法,需要导入lombok包
@NoArgsConstructor
作用在实体类上,生成对应的无参构造方法,需要导入lombok包
@AllArgsConstructor
作用在实体类上,生成对应的有参构造方法,需要导入lombok包
@Param
作为Dao层的注解,作用是用于传递参数,从而可以与SQL中的的字段名相对应,一般在2=<参数数<=5时使用最佳。
示例:
public List<Role> findRoleByAnnotation(@Param("roleName") String roleName, @Param("note") String note);
<select id="findRoleByMap" parameterType="map" resultType="role">
SELECT id,name FROM t_role
WHERE roleName=#{roleName}
AND note=#{note}
<select>
@Resource
@Resource和@Autowired注解都是用来实现依赖注入的。只是@AutoWried按by type自动注入,而@Resource默认按byName自动注入。
@Resource有两个重要属性,分别是name和type
spring将name属性解析为bean的名字,而type属性则被解析为bean的类型。所以如果使用name属性,则使用byName的自动注入策略,如果使用type属性则使用byType的自动注入策略。如果都没有指定,则通过反射机制使用byName自动注入策略。
示例:
@Resource (name= "baseDao" )
private BaseDao baseDao;
@ControllerAdvice
是一个增强的 Controller。使用这个 Controller ,可以实现三个方面的功能:
- 全局异常处理
- 全局数据绑定
- 全局数据预处理
异常集中处理,更好的使业务逻辑与异常处理剥离开;其是对Controller层进行拦截
注意事项:
一个Controller下多个@ExceptionHandler上的异常类型不能出现一样的,否则运行时抛异常.
@ExceptionHandler method mapped for;
@ExceptionHandler下方法返回值类型支持多种,常见的ModelAndView,@ResponseBody注解标注,ResponseEntity等类型都OK.
示例:
@ControllerAdvice
@ResponseBody
public class ErrorController {
}
@ExceptionHandler
统一处理某一类异常,从而能够减少代码重复率和复杂度
示例:
/**
* 统一错误处理
*/
@ControllerAdvice
@ResponseBody
public class ErrorController {
@ExceptionHandler(Exception.class)
public RequestResults customException(Exception e) {
RequestResults results = new RequestResults();
results.setCode(RequestStatusEnum.SYSTEM_ERROR.getCode());
results.setMsg(RequestStatusEnum.SYSTEM_ERROR.getMsg());
results.setSystemErrorMsg(e.getMessage());
results.setData(e.getMessage());
e.printStackTrace();
return results;
}
}
@ResponseStatus
可以将某种异常映射为HTTP状态码
AOP注解:
@Aspect
作用是把当前类标识为一个切面供容器读取
@Before
前置通知, 在方法执行之前执行
@After
后置通知, 在方法执行之后执行,final增强,不管是抛出异常或者正常退出都会执行
@AfterRunning
返回通知, 在方法返回结果之后执行,方法正常退出时执行
@AfterThrowing
异常通知, 在方法抛出异常之后
异常抛出增强,相当于ThrowsAdvice
@Around
环绕通知, 围绕着方法执行
@Aspect
@Component
public class PostDataAspect {
@Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
public void post() {}
@Around("post()")
public Object around(ProceedingJoinPoint point) throws Throwable {
//执行方法
Object result = point.proceed();
//如果是返回的结果对象就直接返回
if(result instanceof RequestResults){
return result;
}
return RequestResults.success(result);
}
}
@Pointcut
Pointcut是植入Advice的触发条件。每个Pointcut的定义包括2部分,一是表达式,二是方法签名。方法签名必须是 public及void型。可以将Pointcut中的方法看作是一个被Advice引用的助记符,因为表达式不直观,因此我们可以通过方法签名的方式为 此表达式命名。因此Pointcut中的方法只需要方法签名,而不需要在方法体内编写实际代码。
切入点,指定说明匹配的方法或者是
示例:
定义了这个
@Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
public void post() {}
定义了这个包及子包下面的所有方法进行匹配
public class AopPointcutClass {
@Pointcut("execution(* com.spring.service..*(..))")
public void logsMean(){}
}
@AfterReturning
后置增强,相当于AfterReturningAdvice,方法正常退出时执行
@ComponentScan
示例:
1.创建一个配置类,在配置类上添加 @ComponentScan 注解。该注解默认会扫描该类所在的包下所有的配置类,相当于之前的 <context:component-scan>。
@ComponentScan(value = "io.mieux.controller")
public class BeanConfig {
}
2.basePackageClasses属性会去扫描类所在包下的所有组件,而不是指定某个组件!
basePackages 属性会扫描指定的组件,也可以指定当前类的所有组件
但得写成:<context:component-scan base-package="controller.**" />
综上, 可以分析出,**匹配任意class文件和包,而*只能匹配包,因此无法扫描到包下的类,因此也就无法被Spring管理。
@ComponentScan(basePackages = {
"com.common.config.aspect"
,"com.common.config.error"
,"com.common.config.auth"
}, basePackageClasses = AutoDriveApplication.class)
@Primary
@Primary 告诉spring 在犹豫的时候优先选择哪一个具体的实现。
在有多个实现类在自动注入时,
@PostConstruct
用于指定初始化方法(用在方法上)
@PreDestory
用于指定销毁方法(用在方法上)
@EnableWebSocket
@ServerEndpoint
这个注解指明了Encoders and Decoders(编码器和解码器)
@KafkaListener
@KafkaListeners是@KafkaListener的Container Annotation,这也是jdk8的新特性之一,注解可以重复标注。
@KafkaListener(topics = { "topic1","topic2","topic3"})
public void listen(ConsumerRecord<?, ?> consumerRecord) {
}
Cloud注解
@EnableEurekaClient
注解在微服务的启动类上面。表示他是Eureka的客户端
@EnableDiscoveryClient
注解在微服务的启动类上面,扫描到服务
@EnableDiscoveryClient和@EnableEurekaClient共同点就是:都是能够让注册中心能够发现,扫描到改服务。
不同点:@EnableEurekaClient只适用于Eureka作为注册中心,@EnableDiscoveryClient 可以是其他注册中心。