聲明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(); }