babababalala
NGUlycc
2019-01-07 09:34

如何通过注解实例化对象?

  • java

我这个实现绕地球一周又回来了,还不如直接注入Map。有简单的解决思路吗

这是自定义的注解

@Target({ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface AutoChooseService {
}

我想通过这个注解实例化service
@RestController
@RequestMapping("/user")
public class UserController {

private final String SERVICE_TYPE = "SERVICE_TYPE";

@AutoChooseService
private UserService userService;

@Autowired
private HttpServletRequest request;

@GetMapping("/create")
public void createUser() {
    userService.createUser("1265");
}

@GetMapping("/init/{type}")
public String setSessionValue(@PathVariable String type, HttpServletRequest request) {
    request.getSession().setAttribute(SERVICE_TYPE,type);
    return "ok";
}

public void choose() {

// HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String type = (String) request.getSession().getAttribute(SERVICE_TYPE);
if (type == null) {
throw new RuntimeException("Errer Code 123");
}
if(type.equalsIgnoreCase("db")){
userService = new UserServiceByDBImpl();
} else if (type.equalsIgnoreCase("file")) {
userService = new UserServiceByFileImpl();
} else {
throw new RuntimeException("Errer Code 123");
}
}
}

那么切面这块该怎么写呢

@Before("@annotation(com.hand.demo1.annotation.AutoChooseService)")
public UserService setService(JoinPoint point) {
    return new UserServiceByDBImpl();
}

@Pointcut(value = "execution(* com.hand.demo1.controller.UserController.*User(..))")
public void cut1() {
}

@Before("cut1()")
public void print(JoinPoint point) throws Exception {
    Class cls = point.getTarget().getClass();

    Field[] fields = cls.getDeclaredFields();
    for(Field field : fields) {
        String fieldName = field.getName();
        if(fieldName.matches("^\\w+Service$")) {
            Annotation[] annotations = field.getDeclaredAnnotations();
            for(Annotation annotation : annotations) {
                if( annotation instanceof AutoChooseService ){
                    Method m = cls.getDeclaredMethod("choose");
                    m.invoke(point.getTarget());
                }
            }
        }
    }
}

}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

1条回答