“约定大于配置”,这是springboot显著特点,它提供了各式各样的注解极大简化代码,建议收藏,方便随时查看。
依赖注入
组件注解
@component,而其余 @Controller、@Service、@Repository都组合了@component注解,主要为便于使用者Class组件进行归类。默认加载IOC容器中的组件,容器启动会调用无参构造器创建对象,再进行初始化赋值等操作
注解 | 解释 | 用的位置 |
---|
@component | 组件注解,使用了该注解会基于注释的配置和类路径扫描时,会自动扫描并加载Class到ICO容器中 | 类 |
@Controller | 应用在MVC层(控制层)DispatcherServlet会自动扫描注解了此注解的类,然后将web请求映射到注解了@RequestMapping的方法上 | 类 |
@Service | 应用在service层(业务逻辑层) | 类 |
@Repository | 应用在dao层(数据访问层) | 类 |
依赖注入注解
@Autowired和@Inject、@Resource,可以与@Qualifier或者@Name配合使用,防止多实例注入时出错,以及值注入@Value。
注解 | 解释 | 用的位置 |
---|
@Autowired | 通过AutowiredAnnotationBeanPostProcessor类实现的依赖注入,默认是根据类型进行注入的,因此如果有多个类型一样的Bean候选者,则需要限定其中一个候选者,否则将抛出异常。 | 类/方法 |
@Inject | 作用与@Autowired一样 | 类/方法/构造器 |
@Resource | 默认按照名称进行装配,名称可以通过name属性进行指定) | 类/方法 |
@Qualifier | 限定描述符除了能根据名字进行注入,更能进行更细粒度的控制如何选择候选者,可与@Autowired或者@Inject进行组合使用,进行精确注入 | 类/方法/参数/注解 |
作用域和生命过程
@Scope,具有4个作用域可看Scope作用域以及涉及的问题章节,以及生命周期过程处理@PostConstruct、@PreDestroy。
注解 | 解释 | 用的位置 |
---|
@Scope | 具有4个作用域singleton,prototype,session,request,默认为singleton单例模式。 | Class创建时 |
@PostConstruct | 相当于init-method,使用在方法上,当Bean初始化时执行 | 方法 |
@PreDestroy | 相当于destory-method,使用在方法上,当Bean销毁时执行 | 方法 |
示例代码
@Service
@Scope("prototype")
public class UseFunctionService {
@Autowired
@Qualifier("functionService")
FunctionService functionService;
@Resource(name="baseDao")
private BaseDao baseDao;
@Inject
@Qualifier("userServiceImpl")
public IUserService userService;
@PostConstruct
public postConstruct(){
System.out.println("postConstruct");
}
@PreDestroy
public perDestroy(){
System.out.println("perDestroy");
}
@Autowired
public void setUserDao(@Qualifier("userDao") UserDao userDao) {
this.userDao = userDao;
}
public String SayHello(String word){
return functionService.sayHello(word);
}
}
配置注解
@Configuration配置注解
@Configuration可替换xml配置文件进行配置。被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。可与@PropertySource一起使用。@Configuration作为元注解延伸了@SpringBootConfiguration。
注解 | 解释 | 用的位置 |
---|
@Configuration | 配置类注解,可以与@Beae、@PropertySource一起使用,进行配置 | 类/接口/枚举 |
@SpringBootConfiguration | 组合注解,@Configuration配置、@EnableAutoConfiguration启用自动配置、@ComponentScan默认扫描@SpringBootApplication所在类的同级目录以及它的子目录 | 类 |
@AutoConfigureAfter | 在指定的自动配置类之后再配置 | 类 |
扫描注解
@ComponentScan注解,被@Configuration注解标注的类上面,涉及了@filter过滤器注解
注解 | 解释 | 用的位置 |
---|
@ComponentScan | 定义扫描的路径,默认就会加载标识了@Controller,@Service,@Repository,@Component注解的类到spring容器中,excludeFilters 指定扫描的时候需要排除的组件,includeFilters 指定扫描的时候只包含的组件 | 类 |
@ComponentScans | 包含着@ComponentScan数组 | 类 |
@filter | 声明要用作包含过滤器或排除过滤器的类型过滤器 | 可注解在@ComponentScan中 |
资源、值等注入注解
可以将配置文件、配置文件中的属性、以及系统属性等注入所需的字段中,或者bean中。
注解 | 解释 | 用的位置 |
---|
@Value | 值注入,可以注入普通字符,系统属性,表达式运算结果,其他Bean的属性,文件内容,网址请求内容,配置文件属性值等等 | 可注释在字段上,方法上、参数上 |
@Bean | 声明当前方法的返回值为一个Bean,而且返回的Bean对应的类中可以定义init()方法和destroy()方法,然后在@Bean(initMethod=”init”,destroyMethod=”destroy”)定义,在构造之后 | 执行init,在销毁之前执行destroy |
@PropertySource | 指定配置文件位置,与@configuration类一起使用 | 注解在类Class、接口上 |
@ImportResource | 加载xml配置文件 | 注解在类Class、接口上 |
@ConfigurationProperties | 将properties属性与一个Bean及其属性相关联 | 注解在类Class、接口上 |
@Import | 用来导入配置类的 | 注解在类Class、接口上 |
条件注解 @Conditional
@Conditional根据满足某一特定条件创建特定的Bean,基于@Conditional元注解可延伸很多条件注解
注解 | 解释 | 用的位置 |
---|
@ConditionalOnBean | Spring容器中是否存在对应的实例,可以通过实例的类型、类名、注解、昵称去容器中查找(可以配置从当前容器中查找或者父容器中查找或者两者一起查找)这些属性都是数组,通过”与”的关系进行查找 | 可注解方法上 |
@ConditionalOnClass | 类加载器中是否存在对应的类,逻辑跟@ConditionalOnBean类似 | 可注解在方法上、类Class、接口上 |
@ConditionalOnExpression | 判断SpEL 表达式是否成立 | 可注解在方法上、类Class、接口上 |
@ConditionalOnJava | 指定Java版本是否符合要求 | 可注解在方法上、类Class、接口上 |
@ConditionalOnMissingBean | Spring容器中是否缺少对应的实例,逻辑跟@ConditionalOnBean类似 | 可注解在方法上、类Class、接口上 |
@ConditionalOnMissingClass | Spring容器中是否缺少对应的实例,逻辑跟@ConditionalOnBean类似 | 可注解在方法上、类Class、接口上 |
@ConditionalOnNotWebApplication | 应用程序是否是非Web程序,没有提供属性,只是一个标识 | 可注解在方法上、类Class、接口上 |
@ConditionalOnProperty | 应用环境中的屬性是否存在,逻辑跟@ConditionalOnBean类似 | 可注解在方法上、类Class、接口上 |
@ConditionalOnResource | 是否存在指定的资源文件。只有一个属性resources,是个String数组。会从类加载器中 | 去查询对应的资源文件是否存在可 注解在方法上、类Class、接口上 |
@Profile | 指定某个bean属于哪一个profile:spring.profiles.active | 和spring.profiles.default(默认) |
示例代码
@Configuration
@ComponentScan(value="com.cn",ComponentDefaultFilters=true,
includeFilters={
@Filter(type=FilterType.ANNOTATION,classes={Controller.class}),
@Filter(type=FilterType.CUSTOM,classes={MyTypeFilter.class})
})
@ImportResource("classpath:condition.xml")
@Import(ConditionConfig.class)
public class Config {
@Value("I Love You!")
private String normal;
@Value("#{systemProperties['os.name']}")
private String osName;
@Value("#{ T(java.lang.Math).random() * 100.0 }")
private double randomNumber;
@Value("#{demoService.another}")
private String fromAnother;
@Value("classpath:org/light4j/sping4/usually/el/test.txt")
private Resource testFile;
@Value("http://www.baidu.com")
private Resource testUrl;
@Value("${book.name}")
private String bookName;
@Bean
@Conditional(WindowsCondition.class)
@ConditionalOnResource(resources="classpath:windows.ini")
public ListService windowsListService(){
return new WindowsListService();
}
@Bean
@ConditionalOnClass(LinuxCondition.class)
@ConditionalOnProperty(name = "synchronize", havingValue = "true"))
public ListService linuxListService(){
return new LinuxListService();
}
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource jwcDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
@ConditionalOnMissingClass({LinuxCondition.class,WindowsCondition.class})
@Profile("dev")
public ListService macListService(){
return new MacListService();
}
}
验证注解
验证注解在javax.validation包下:
注解 | 解释 | 用的位置 |
---|
@Valid | 启动校验,Errors参数要紧跟在带有@Valid注解的参数后面,@Valid注解所标注的就是要检验的参数 | 可注释在字段、方法、构造器、参数上 |
@AssertFalse | 所注解的元素必须是Boolean类型,并且值为false | 可注释在字段、方法、构造器、参数上 |
@AssertTrue | 所注解的元素必须是Boolean类型,并且值为true | 可注释在字段、方法、构造器、参数上 |
@DecimalMax | 所注解的元素必须是数字,并且它的值要小于或等于给定的BigDecimalString值 | 可注释在字段、方法、构造器、参数上 |
@DecimalMin | 所注解的元素必须是数字,并且它的值要大于或等于给定的BigDecimalString值 | 可注释在字段、方法、构造器、参数上 |
@Digits | 所注解的元素必须是数字,并且它的值必须有指定的位数 | 可注释在字段、方法、构造器、参数上 |
@Future | 所注解的元素的值必须是一个将来的日期 | 可注释在字段、方法、构造器、参数上 |
@Max | 所注解的元素必须是数字,并且它的值要小于或等于给定的值 | 可注释在字段、方法、构造器、参数上 |
@Min | 所注解的元素必须是数字,并且它的值要大于或等于给定的值 | 可注释在字段、方法、构造器、参数上 |
@NotNull | 所注解元素的值必须不能为null | 可注释在字段、方法、构造器、参数上 |
@Null | 所注解元素的值必须为null | 可注释在字段、方法、构造器、参数上 |
@Past | 所注解的元素的值必须是一个已过去的日期 | 可注释在字段、方法、构造器、参数上 |
@Pattern | 所注解的元素的值必须匹配给定的正则表达式 | 可注释在字段、方法、构造器、参数上 |
@Size | 所注解的元素的值必须是String、集合或数组,并且它的长度要符合给定的范围 | 可注释在字段、方法、构造器、参数上 |
AOP
AspectJ的注解式切面编程:
AspectJ的注解式在org.aspectj包下
注解 | 解释 | 用的位置 |
---|
@Aspect | 声明该类是一个切面 | 可注解在类Class、接口上 |
@After | 通知方法会在目标方法返回或抛出异常后调用 | 可注解在方法上 |
@Before | 通知方法会在目标方法调用之前执行 | 可注解在方法上 |
@Around | 通知方法会将目标方法封装起来 | 可注解在方法上 |
@AfterReturning | 通知方法会在目标方法返回后调用 | 可注解在方法上 |
@AfterThrowing | 通知方法会在目标方法抛出异常后调用 | 可注解在方法上 |
@Pointcut | 能够在一个@AspectJ切面内定义可重用的切点,(通过@Pointcut注解声明频繁使用的切点表达式) | 可注解在方法上 |
@annotation | 限定匹配带有指定注解的连接点 | 可注解在建言(advice)上,如@After等 |
@EnableAspectJAutoProxy | 开启Spring对AspectJ的支持,在配置类上 | 可注解在类Class、接口上 |
AspectJ指示器
execution指示器是我们在编写切点定义时最主要使用的指示器:
注解 | 解释 | 用的位置 |
---|
arg() | 限制连接点匹配参数为指定类型的执行方法 | 可注释在AspectJ的注解式、如@After等 |
@args() | 限制连接点匹配参数由指定注解标注的执行方法 | 可注释在AspectJ的注解式,如@After等 |
execution() | 用于匹配是连接点的执行方法 | 可注释在AspectJ的注解式,如@After等 |
this() | 限制连接点匹配AOP代理的bean引用为指定类型的类 | 可注释在AspectJ的注解式,如 |
Target | 限制连接点匹配目标对象为指定类型的类 | 可注释在AspectJ的注解式,如@After等 |
@target() | 限制连接点匹配特定的执行对象,这些对象对应的类要具有指定类型的注解 | 可注释在AspectJ的注解式,如@After等 |
within() | 限制连接点匹配指定的类型 | 可注释在AspectJ的注解式,如@After等 |
@within() | 限制连接点匹配指定注解所标注的类型(当使用Spring AOP时,方法定义在由指定的注解所标注的类里) | 可注释在AspectJ的注解式,如@After等 |
用例:编写切面
@Aspect
@Component
public class LogAspect {
private final String POINT_CUT ="execution(* org.sping4.ccww.aop.DemoMethodService.*(..))";
@Pointcut("@annotation(org.ccww.sping4.base.aop.Action)")
public void annotationPointCut(){};
@After("annotationPointCut()")
public void after(JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Action action = method.getAnnotation(Action.class);
System.out.println("注解式拦截 " + action.name());
}
@Before("execution(* org.sping4.ccww.aop.DemoMethodService.*(..))")
public void before(JoinPoint joinPoint){
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
System.out.println("方法规则式拦截,"+method.getName());
}
@AfterReturning(value = POINT_CUT,returning = "result")
public void doAfterReturningAdvice1(JoinPoint joinPoint,Object result){
System.out.println("第一个后置返回通知的返回值:"+result);
}
}
Spring MVC
注解 | 解释 | 用的位置 |
---|
@EnableWebMvc | 会开启一些默认配置,如一些ViewResolver或者MessageConverter等 | 可注解在 |
@RequestMapping | 用来映射Web请求(访问路径和参数),处理类和方法的(即配置URL和方法之间的映射),注解在方法上的@RequestMapping路径会继承注解在类上的路径 | 可注解在类Class、接口上、方法上 |
@ResponseBody | 支持将返回值放在response体内 | 可注解在返回值前或者方法上 |
@RequestBody | 允许requ est的参数在request体内 | 可注解在参数或者方法上 |
@PathVariable | 用来接收路径参数,如/ccww/003,可接收003作为参数 | 可注解在参数前 |
@RestController | 组合注解,组合了@Controller和@ResponseBody,这就意味着当你只开发一个和页面交互数据的控制的时候,需要使用此注解。若没有此注解,要想实现上述功能,则需要自己在代码中加@Controller和@ResponseBody两个注解 | 可注解在类Class、接口上 |
@ModelAttribute | 绑定请求参数到命令对象、暴露@RequestMapping 方法返回值为模型数据、暴露表单引用对象为模型数据 | 可注解在方法、参数上 |
Spring security
Spring security用户访问认证和授权,两个关键注解:
注解 | 解释 | 用的位置 |
---|
@EnableWebSecurityConfig | 该注解和@Configuration注解一起使用,注解 WebSecurityConfigurer类型的类,或者利用@EnableWebSecurity注解继承WebSecurityConfigurerAdapter的类,这样就构成了Spring Security的配置 | 可注解在Class上 |
@EnableGlobaleMethodSecurity | Spring security默认是禁用注解的,要想开启注解,需要继承WebSecurityConfigurerAdapter的类上加@EnableGlobalMethodSecurity注解,来判断用户对某个控制层的方法是否具有访问权限 | 可注释在Class上 |
Spring Boot
注解 | 解释 | 用的位置 |
---|
@SpringBootApplication | Spring Boot核心注解,组合注解(@Configuration、 | @EnableAutoConfiguration、@ComponentScan),主要是为了开启自动配置 |
@EnableAutoConfiguration | 让Spring Boot根据类路径中的jar包依赖为当前项目进行自动配置 | 可注释在Class、interface上 |