AOP
@Aspect @Component public class LogAspect { @Pointcut("@annotation(com.sys.aop.point)") // point 自定义注解 public void annotationPointCut(){}; @After("annotationPointCut()") public void after(JoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); Point action = method.getAnnotation(Point.class); System.out.println(action.name()); } //@Before("execution(*com.sys.aop.DemoService.*(..))") }
aware
public class AwareService implements BeanNameAware, ResourceLoaderAware{ private String beanName; private ResourceLoader loader; @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.loader = resourceLoader; } @Override public void setBeanName(String name) { this.beanName = name; } public void outputResult() { System.out.println("Bean 的名称为:"+beanName); Resource resource = loader.getResource("classpath:com/sys/a.txt"); try { System.out.println(IOUtils.toString(resource.getInputStream())); } catch (Exception e) { e.printStackTrace(); } } }
多线程
@Configuration @EnableAsync public class TaskExecutorConfig implements AsyncConfigurer{ @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor(); taskExecutor.setCorePoolSize(5); taskExecutor.setMaxPoolSize(10); taskExecutor.setQueueCapacity(25); taskExecutor.initialize(); return taskExecutor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return null; } }
@Service public class AsyncService { @Async public void executeAsync() { } @Async public void executeAsyncPlus() { } }
计划任务
@Service @EnableScheduling public class ScheduleTaskService { private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("HH:mm:ss"); @Scheduled(fixedRate = 5000) public void reportCurrentTime() { System.out.println("每隔5秒执行一次"); } //@Scheduled(cron = "0 28 11 ? * *") 每天11点28执行 } //再在配置类上加上 @EnbleScheduling
条件注解@Conditional
实现Condition接口,实现matches方法 返回boolean值
@Enable*注解的原理
@Target(value = {ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(value = {FirstFilterConfiguration.class}) public @interface EnableFirstFilter { }
过滤器
public class FirstFilterConfiguration { public static final Integer ORDER = Integer.MIN_VALUE; @Bean public FilterRegistrationBean firstFilter(){ FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new FirstFilter()); registration.addUrlPatterns("/*"); registration.setName("firstFilter"); registration.setOrder(ORDER); return registration; } }
@Target(value = {ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(value = {TokenPropery.class, AuthenticationIgnoreProperty.class, ClientKeyPropery.class}) @EnableConfigurationProperties(value= {PagesAccessPropery.class}) public @interface EnableProperties { }
@RequestingMapping(value={"/obj", "/obj2"}, produces = "application/json;charset=UTF-8")
webMVC 及拦截器的配置
@Configuration @EnableWebMvc public class MyMvcConfig extends WebMvcConfigurerAdapter{ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/asserts/**").addResourceLocations("classpath:/asserts/"); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HandlerInterceptor() { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // TODO Auto-generated method stub return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub } }); } }
@ControllerAdvice public class ExceptionHandlerAdvice { @ExceptionHandler(value = Exception.class) public ModelAndView exception(Exception e) { ModelAndView modelAndView = new ModelAndView("error"); modelAndView.addObject("error", e.getMessage()); return modelAndView; } @ModelAttribute 将此信息放入全局 public void addAttributes(Model model) { model.addAttribute("msg","ewaixinxi"); } @InitBinder public void initBinder(WebDataBinder webDataBinder){ webDataBinder.setDisallowedFields("id"); } }
spring boot
@SpringBootApplication 包含了
@EnableAutoConfiguration
@ComponentScan 注解
对于application.properties的属性注入
@ConfigurationProperties(prefix=“前缀”) 加载文件的位置 @value
spring.profiles.active=设定活动的properties
springboot 运行原理
java - jar **.jar --debug 或者application.properties debug=true
@SpringBootApplication的注解上@EnableAutoConfiguration 引入了EnableAutoConfigurationImportSelector.class
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { List<String> configurations = SpringFactoriesLoader.loadFactoryNames( getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader()); Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you " + "are using a custom packaging, make sure that file is correct."); return configurations; }
对META——INF/spring.factories下的文件扫描需要加载配置的类
@ConfigurationProperties(prefix="")
@EnableConfigurationProperties(配置类) 声明后,再通过@autowried注入
@ConditionalOnProperty(prefix="", value="enabled",matchMissing=true)
替换使用jetty
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency>