声明bean的注解java
例子: FunctionService.java数据库
@Service public class FunctionService { public String sayHello(String content){ return "Hello "+content; } }
UseFunctionService.java编程
@Service public class UseFunctionService { @Autowired FunctionService functionService; public String sayHello(String content){ return functionService.sayHello(content); } }
DiConfig.java(配置类,做为元数据)测试
@Configuration @ComponentScan("com.flexible")//扫描包 public class DiConfig { }
测试代码flex
AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext(DiConfig.class); UseFunctionService u = configApplicationContext.getBean(UseFunctionService.class); String test = u.sayHello("test"); System.out.println(test);
执行结果:.net
Java配置是Spring4.x推荐的配置方式,这种配置方式彻底能够替代xml配置,Java配置也是SpringBoot推荐的配置方式。从上面的例子能够知道Java配置使用@Configuration和@Bean来实现。@Configuration声明一个类至关于S的xml配置文件,使用@Bean注解在方法上,声明当前方法的返回值作为一个Bean.3d
全局配置使用Java配置(如数据库的相关配置,MVC香关配置),业务Bean的配置使用注解配置(@Service,@Compoent,@Repository,@Controller)code
SpringAOP存在目的就是为了给程序解耦,AOP能够让一组类共享相同的行为,实现了OOP没法实现的一些功能,在必定程度上弥补了OOP的短板.xml
Spring支持AspectJ的注解式编程blog
例子: 注解方法 DemoAnnotationService.java @Service public class DemoAnnotationService {
@Action(value = "注解拦截的当前的add方法") public void add() { } }
没用注解的方法的类
@Service public class DemoMethodService { public void add() { } }
Action.java(注解类)
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Action { String value(); }
LogAspect.java(定义切面)
@Component @Aspect public class LogAspect { //命名一个切点 @Pointcut("@annotation(com.flexible.annotation.Action)") public void annotationPointcut() { } @After("annotationPointcut()") public void after(JoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); String name = method.getName(); System.out.println("after注解拦截了 " + name); } @Before("execution(* com.flexible.service.DemoMethodService.*(..))") public void before(JoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); String name = method.getName(); System.out.println("before注解拦截了 " + name); } }
测试代码
@Test public void testMethod(){ AnnotationConfigApplicationContext configApplicationContext = new AnnotationConfigApplicationContext(AopConfig.class); DemoAnnotationService annotationService = configApplicationContext.getBean(DemoAnnotationService.class); annotationService.add(); DemoMethodService demoMethodService = configApplicationContext.getBean(DemoMethodService.class); demoMethodService.add(); }