@Componentspring
@Aspect.net
public class Internet {code
@Pointcut("execution( * com.cheng.spring.ShowSalery.*(..))") public void showSalary() {} @Before(value = "showSalary()") public void checkInternet() throws UnknownHostException { InetAddress localHost = InetAddress.getLocalHost(); System.out.println("ip-----" + localHost); }
@Componentxml
@Aspectip
public class Logger {get
@Pointcut("execution( * com.cheng.spring.ShowSalery.*(..))") public void showSalary() {} @Before(value = "showSalary()") public void log() { System.out.println("操做時間-----"+new Date()); }
}io
自定義註解 @Retention(RetentionPolicy.RUNTIME)class
@Target(ElementType.METHOD)test
public @interface PrivilegeAnnotation {date
String privilege() default "";
@Component("privilege")
@Aspect
public class PrivilegeAscpect {
@Autowired private List<User> users; @Pointcut("execution( * com.cheng.spring.ShowSalery.*(..))") public void showSalary() {} // 環繞通知 可用來控制權限 @Around(value = "showSalary()") public void isAccess(ProceedingJoinPoint point) throws Throwable { boolean flag = false; Class<? extends Object> class1 = point.getTarget().getClass(); String name = point.getSignature().getName(); Method declaredMethod = class1.getDeclaredMethod(name); declaredMethod.setAccessible(true); boolean annotationPresent = declaredMethod.isAnnotationPresent(PrivilegeAnnotation.class); if (annotationPresent) { PrivilegeAnnotation annotation = declaredMethod.getAnnotation(PrivilegeAnnotation.class); // 註解上的值 String privilege = annotation.privilege(); if (name.equals("showSalery")) { for (User user : users) { if (user.getName().equals(privilege)) { point.proceed(); } else { System.out.println("你無權查看"); } } } else { point.proceed(); } } }
@Component("showsalery")
public class ShowSalery {
@PrivilegeAnnotation(
privilege="admin")
public void showSalery() { System.out.println("工資爲100000$"); } @PrivilegeAnnotation(privilege="admin") public void updateSalery() { System.out.println("調整工資"); }
@Component("user")
public class User {
@Value("admin") private String name; public String getName() { return name; }
public class ShowSaleryTest {
@Test public void testShowSalery() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans3.xml"); ShowSalery bean = context.getBean("showsalery",ShowSalery.class); bean.showSalery(); }
}