java 注解示例
*********************
示例:自定义注解为对象赋值
***************
annotation 层
CustomAnnotation
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
String value() default "";
}
***************
pojo 层
Person
@Component
public class Person {
private String name;
private Integer age;
@CustomAnnotation("瓜田李下")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@CustomAnnotation("24")
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return this.name+" "+this.age;
}
}
***************
aop 层
CustomAspect
@Aspect
@Component
public class CustomAspect {
@Pointcut("@annotation(com.example.demo.annotation.CustomAnnotation)")
public void fun(){
}
@Before("fun()")
public void before(JoinPoint joinPoint){
Person person=(Person) joinPoint.getTarget();
MethodSignature methodSignature=(MethodSignature) joinPoint.getSignature();
Method method=methodSignature.getMethod();
CustomAnnotation customAnnotation=method.getAnnotation(CustomAnnotation.class);
if (method.getName().equals("getName")){
if (person.getName()==null){
person.setName(customAnnotation.value());
}
}else {
if (person.getAge()==null){
person.setAge(Integer.parseInt(customAnnotation.value().toString()));
}
}
}
}
***************
controller 层
HelloController
@RestController
public class HelloController {
@Autowired
private Person person;
@RequestMapping("/hello")
public void hello(){
System.out.println(person.getName()+" "+person.getAge());
}
}
*********************
控制台输出
2019-11-16 10:26:16.116 INFO 23704 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-11-16 10:26:16.116 INFO 23704 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-11-16 10:26:16.124 INFO 23704 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 8 ms
瓜田李下 24