파일 경로 : src/main/java - com.kh.aop - LogAspect
@Aspect
@Log4j // 로깅의 라이브러리
@Component // 스프링 빈에 등록하는 역할
public class LogAspect {
@Before("execution(* com.kh.service.SampleService*.*(..)))") // before는 "execution"라고 지정해주는 형태
// @Before 어드바이스: 지정한 포인트컷(메서드 실행 시점) 전에 실행될 코드를 정의합니다.
// execution(* com.kh.service.SampleService*.*(..)))는 패키지 com.kh.service 내의
// 클래스명이 SampleService로 시작하는 모든 메서드에 대한 실행을 가리킵니다.
public void logBefore() {
log.info("===============");
// 로깅 라이브러리에 저장되어 있는 메소드
// 로그의 정보가 정상적으로 출력되면 ("===============") 안의 내용이 출력된다.
}
@Before("execution(* com.kh.service.SampleService*.doAdd(String, String)) && args(str1, str2)")
// 메서드명이 doAdd이고 타입이 String이고 변수명이 str1, str2 로 일치해야 한다.
public void logBeforeWithParam(String str1, String str2) {
log.info("str1 : " + str1);
log.info("str2 : " + str2);
}
}
파일 경로: src/main/java - com.kh.service - SampleService
@Service // 이 서비스 안에 @component 가 포함되어 잇음
public class SampleService {
// int가 아닌 Integer을 쓰는 이유 : int는 0을 반환하지만 Integer는 null을 반환하여 null 조건처리를 할 수 있음
public Integer doAdd(String str1, String str2) throws Exception{
return Integer.parseInt(str1) + Integer.parseInt(str2);
}
}
파일경로 : src/main/webapp/WEB-INF/spring/appServlet/root-context.xml
<!-- Root Context: defines shared resources visible to all other web components -->
<context:annotation-config></context:annotation-config>
<!-- 어떤 컴포넌트를 스캔할 것인가 -->
<context:component-scan base-package="com.kh.aop"></context:component-scan>
<context:component-scan base-package="com.kh.service"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
root-context.xml에서 Bean graph를 보면 두 가지의 빈(객체)들이 올라가 있는 것을 볼 수 있다.

@RunWith(SpringJUnit4ClassRunner.class)
@Log4j
@ContextConfiguration({"file:src/main/webapp/WEB-INF/spring/root-context.xml"})
public class SampleServiceTest {
// onMethod_ 를 씀으로써 다른 어노테이션(속성)을 쓸 수 있음-> @Autowired 속성 추가
@Setter(onMethod_ = @Autowired) // @Autowired : SampleService 클래스를 스프링에 Bean으로 자동으로 주입되도록 도와주는 역할(해당 클래스에 @component를 설정해야 스프링의 빈으로 등록 가능 )
private SampleService service;
@Test
public void testClass() {
log.info(service);
log.info(service.getClass().getName());
}
@Test
public void testAdd() throws Exception{
log.info(service.doAdd("123", "456"));
}
}