Spring Boot @Aspect J logging

时间:2016-04-06 16:23:29

标签: java spring-mvc spring-boot aop

我使用REST控制器创建了测试Spring MVC应用程序。我想为我的某些方法应用方面,但是当调用此方法时没有任何事情发生,我找不到原因。 这是我的配置和应用程序类:

@SpringBootApplication(scanBasePackages = "org.test")
@EnableAspectJAutoProxy
public class TestaopApplication {

public static void main(String[] args) {
    SpringApplication.run(TestaopApplication.class, args);
}
}

这是我的方面课程:

@Aspect
@Component
public class Logging {

private static final Logger logger = LoggerFactory.getLogger(GreetingController.class);
@Pointcut("execution(* org.test.restspring.model.Greeting.getCreatedDate(..))")
private void getDate(){}

@Before("getDate()")
public void beforeGettingDate(){
    logger.info("Date is asked");
}

@After("getDate()")
public void afterGettingDate(){
    logger.info("Date is received");
}

}

这是我的简单豆子:

@Component
public class Greeting {

private long id;
private String content;
private Date created;

public Greeting() { }
public Greeting(long id, String content) {
    this.id = id;
    this.content = content;
    this.created = Calendar.getInstance().getTime();
}

public long getId() {
    return id;
}

public String getContent() {
    return content;
}

public String getCreatedDate(){
    return created.toString();
}
 }

这是我的控制器:

@RestController
public class GreetingController {

private static final String template = "Hello, %s!";
private static final Logger logger = LoggerFactory.getLogger(GreetingController.class);
private final AtomicLong counter = new AtomicLong();

@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
    Greeting response = new Greeting(counter.incrementAndGet(),
            String.format(template, name));
    logger.info(response.getCreatedDate());
    return response;
}


}

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

通过显式构造函数调用(new Greeting(...))创建的Bean不由Spring管理。这就是为什么你的方面没有应用的原因。

您可以尝试使用原型范围。这样Spring就为每个请求创建了问候bean的新实例。

for bean:

@Component
@Scope("prototype")
public class Greeting {

和您的控制人员:

@RestController
public class GreetingController {

private static final String template = "Hello, %s!";
private static final Logger logger = LoggerFactory.getLogger(GreetingController.class);
private final AtomicLong counter = new AtomicLong();

@Autowired
private Greeting greeting;

@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
    greeting.setId(counter.incrementAndGet());
    greeting.setContent(String.format(template, name))
    logger.info(response.getCreatedDate());
    return response;
}



}