Spring Boot学习,熟悉注解和Java式的配置。源代码见Source-Sample-GitHub。
xml
(Spring 1.x) 》》 @annotation
(Spring 2.x+Jdk1.5)》》SpringBoot
就是基于Java配置(注解的应用)
bean
的支持即由Spring容器创建管理Bean(POJO类),通过注解/XML/JAVA告诉容器应该将Bean何时放在何地。
声明Bean:
* @Component 通用
* @Service 在业务逻辑层使用
* @Repository 数据访问层使用
* @Controller 展现层使用
引入Bean:
* @Autowired Spring提供的注解
* @Inject/@Resource JSR-330/JSR-250提供的注解
@Configuration 表示这个类是一个配置类,等效于一个xml文件
@Bean 注解一个方法,将方法返回值注册为一个bean
<context:component-scan base-package="com.controller">context:component-scan>
@ComponentScan("com.controller")
<bean class="com.util.MySwaggerConfig"/>
@Configuration
public class JavaConfig{
@Bean
public MySwaggerConfig mySwaggerConfig(){
return new MySwaggerConfig();
}
}
有两种方式,一个是监听方法(通过配置目标路径),一个是监听注解(在目标方法上放置特殊注解)
* 定义注解,作为被监听的标识
/**
* 注解本身是没有作用的,只是作为一个规则,关联拦截者和被拦截者
*/
@Target(ElementType.METHOD)//用于方法
@Retention(RetentionPolicy.RUNTIME)//可用于运行时
@Documented
public @interface AopAction {
String name();
}
/**
* 注解式拦截,在对应方法上加上@AopAction,在拦截时通过检查注解进行拦截
*/
@Service
public class DemoAnnotationAopService {
@AopAction(name = "注解式AOP")
public String say() {
return "Hello,Annotation World.";
}
}
@Service
public class DemoMethodAopService {
public String say() {
return "Hello, Normal World.";
}
}
/**
* Aop实现的地方
*/
@Aspect//声明一个切面
@Component//托管给Spring容器
public class AspectAopImpl {
private final Logger log = LoggerFactory.getLogger(this.getClass());
/**
* 注解式,通过检查注解位置来拦截
*/
@Pointcut("@annotation(demo.springboot.aop.impl.AopAction)")
public void annotationPointCut() {}
@Before("annotationPointCut()")
public void logBefore() { log.info("logBefore:现在时间是:" + new Date()); }
/**
* 通过指定拦截位置和具体方法
*/
@Pointcut("execution(* demo.springboot.aop.service.DemoMethodAopService.*(..))")
private void methodPointCut() {}
@After("methodPointCut()")
public void logAfter() { log.info("logAfter:现在时间是:" + new Date()); }
}
注入配置文件,开启AspectJ
/**
* 用注解代替了xml
*
*/
@EnableAspectJAutoProxy
@Configuration
@ComponentScan("demo.springboot.aop")//在Application入口整体扫描,可省略此行
public class AopConfiguration {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
/**
* 测试两种Aop
*/
DemoAnnotationAopService annotationAopService = context.getBean(DemoAnnotationAopService.class);
DemoMethodAopService methodAopService = context.getBean(DemoMethodAopService.class);
System.out.println(annotationAopService.say());
System.out.println(methodAopService.say());
context.close();
}
}