본문 바로가기

bitcamp/면접족보

면접족보 21/02/15_ AOP

1. AOP에 대하여 설명하시오.


· Aspect Oriented Programming의 약자로, AOP는 어플리케이션의 로직을 포함하는 핵심적인 기능과 이를 도와주는 부가적인

 기능을 분리한다. 분리한 부가 기능을 Aspect라는 모듈형태로 제작하고, 핵심기능을 설계하여 구현할 때 도와주는 역할을 한다. 

 

※AOP 용어 정리

· Aspect: 공통기능이 들어 있는 클래스
· Advice: Aspect 클래스에 들어 있는 공통기능 (Aspcect의 함수)
· JointPoint: advice 함수가 적용되는 함수 (getList()와 같이 Service에 있는 함수들에 적용)
· PointCut: Jointpoint의 부분으로 실제로 적용되는 함수 내의 지점 
(호출 된 함수를 기준으로 전/후, 중간 어느 시점에

               적용시킬 것인지, before는 함수 호출 전, arround는 함수가 시작하고 종료되는 시점을 나타낸다)

· weaving: Advice를 적용하는 행위 

 

2. AOP를 적용하기 위한 두가지 방법은?

*사용하기 앞서 pom.xml에 아래와 같이 의존 설정

 

1)xml을 이용하여 사용하는 방법

 

<LogAdvice.java>

1
2
3
4
5
 public class LogAdvice {
    public void printLogging() {
        System.out.println("=====로그기록=====");
    }
 }
cs

 

<LogAop.java> 대표적으로 시간 차를 체크하는 방법은 아래와 같다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 public class LogAop {
    public Object loggerAop(ProceedingJoinPoint joinpoint) throws Throwable{  //joinpoint 생성
        String signatureStr = joinpoint.getSignature().toShortString();
        System.out.println(signatureStr + "is start.");
        
        long st = System.currentTimeMillis();
        
        try {
            Object obj = joinpoint.proceed();
            //내가 실행시키려는 로직 getList() 등등, 핵심기능 실행
            
            return obj;
            
        }finally {
            long et = System.currentTimeMillis();
            System.out.println(signatureStr);
            System.out.println(signatureStr + "걸리는 시간" + (et-st));
        }
    }
 }
cs

 

<servlet-context.xml> 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
   <bean id="logAdvice" class="edu.bit.ex.aop.LogAdvice" />  
   <bean id="logAop" class="edu.bit.ex.aop.LogAop" /> 
 
   <aop:config>
       <aop:aspect ref="logAdvice">
           <aop:pointcut id="publicM" expression="within(edu.bit.ex.board.service.*)"/>
           <!-- service에 존재하는 모든 함수에 대해 advice 함수를 적용시키겠다는 의미-->
           <aop:before pointcut-ref="publicM" method="printLogging" />
           <!-- LogAdvice 클래스의 pringLogging 함수를 service 실행하기 전에 적용시킨다는 의미 -->
       </aop:aspect>
   </aop:config>
   
   <aop:config>
       <aop:aspect ref="logAop">
           <!-- pointcut(핵심 기능)의 id는 publicM이고, edu.bit.ex.* 패키지에 있는 모든 클래스에 공통 기능을 적용 -->
           <aop:pointcut id="publicM" expression="within(edu.bit.ex.board.service.*)" />
           <!-- loggerAop()라는 공통 기능을 publicM라는 pointcut에 적용 -->
           <aop:around pointcut-ref="publicM" method="loggerAop" />
       </aop:aspect>
   </aop:config>
 </beans>
cs

 

<출력 화면>

 

2) xml+어노테이션 사용방법

<servlet-context.xml> 어노테이션을 로딩하기 위해 아래의 내용 추가

<LogAdvice2.java>

1
2
3
4
5
6
7
8
9
 @Component
 @Aspect
 public class LogAdvice2 {
    @Before("within(edu.bit.ex.board.service.*)")  //PointCut 설정
    public void printLogging() {
    System.out.println("공통기능2=====로그기록=====");
    }
 }
 
cs

 

<<LogAop2.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 @Component
 @Aspect
 public class LogAop2 {
 
    @Around("within(edu.bit.ex.board.service.*)")  //PointCut 설정
    public Object loggerAop(ProceedingJoinPoint joinpoint) throws Throwable{  //joinpoint 생성
        String signatureStr = joinpoint.getSignature().toShortString();
        System.out.println(signatureStr + "is start.");
        
        long st = System.currentTimeMillis();
        
        try {
            Object obj = joinpoint.proceed();
            //내가 실행시키려는 로직 getList() 등등
            
            return obj;
            
        }finally {
            long et = System.currentTimeMillis();
            System.out.println(signatureStr);
            System.out.println(signatureStr + "걸리는 시간" + (et-st));
        }
    }
 }
cs

 

<출력 화면>

※연습문제※

· emp와 dept의 사원이름과 부서명을 출력하고, url에 부서번호를 입력하는 경우 부서번호에 해당되는 사원을 출력하시오.
 Hint: 마이바티스에서 1:N 처리 방법으로는 resultMap, collection을 사용

 

<empVO.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
@Data
@Getter
@Setter
public class EmpVO {
    int empno;
    String ename;
    String job;
    int mgr;
    Date hiredate;
    int sal;
    int comm;
    int deptno;
}
cs

 

<deptVO.java>

1
2
3
4
5
6
7
8
@Data
public class DeptVO {
    int deptno;
    String dname;
    String loc;
 
    EmpVO empVO;  //1:N 관계에서 N에 해당되는 테이블을 불러온다
}
cs


<RestEmpController.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@Log4j
@AllArgsConstructor
@RestController
@RequestMapping("/emp/*")
public class RestEmpController {
    private EmpService empService;
    
    //shop 구현
    @GetMapping("/list")
    public ModelAndView emplist(ModelAndView mav) {
        log.info("emplist");
        mav.setViewName("emplist");
        mav.addObject("emplist", empService.getEmplist());
 
        return mav;
    }
    
    @GetMapping("/list/{deptno}")
    public ModelAndView deptlist(@PathVariable("deptno"int deptno, EmpVO empVO, ModelAndView mav) {
        log.info("deptlist");
        
        mav.setViewName("deptlist");
        mav.addObject("deptlist", empService.getDeptlist(deptno));
        return mav;
    }
}
cs

 

 

<EmpService.java>

1
2
3
4
5
public interface EmpService {
    public List<EmpVO> getEmplist();
 
    public List<DeptVO> getDeptlist(int deptno);
}
cs

 

<EmpServiceImpl.java>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Log4j
@AllArgsConstructor
@Service
public class EmpServiceImpl implements EmpService{
    private EmpMapper mapper;
 
    @Override
    public List<EmpVO> getEmplist() {
        log.info("getEmplist");
        return mapper.getEmplist();
    }
 
    @Override
    public List<DeptVO> getDeptlist(String deptno){
        log.info("getlistdept");
        return mapper.getDeptlist(deptno);
    }
}
 
cs

 

<EmpMapper.java>

1
2
3
4
5
public interface EmpMapper {
    List<EmpVO> getEmplist();
 
    List<DeptVO> getDeptlist(int deptno);
}
cs

 

<emp.xml>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<mapper namespace="edu.bit.ex.emp.mapper.EmpMapper">
 
<resultMap id="empVO" type="edu.bit.ex.emp.vo.EmpVO">
    <result column="EMPNO" property="empno" />
    <result column="ENAME" property="ename" />
    <result column="JOB" property="job" />
    <result column="MGR" property="mgr" />
    <result column="HIREDATE" property="hiredate" />
    <result column="SAL" property="sal" />
    <result column="COMM" property="comm" />
    <result column="DEPTNO" property="deptno" />        
</resultMap>
 
<resultMap id="deptVO" type="edu.bit.ex.emp.vo.DeptVO"> 
    <result column="DEPTNO" property="deptno" />
    <result column="DNAME" property="dname" />
    <result column="LOC" property="loc" />
    <collection resultMap="empVO" property="empVO" />    
</resultMap>
 
<select id="getEmplist" resultMap="empVO" parameterType="java.util.List">
    <![CDATA[ 
        select * from EMP e, DEPT d where e.deptno=d.deptno 
    ]]>
</select>
 
<select id="getDeptlist" resultMap="deptVO" parameterType="java.util.List">
    <![CDATA[ 
        select * from EMP e, DEPT d where e.deptno=d.deptno and d.deptno=#{deptno}
    ]]>
</select>
</mapper>
cs

 

<emplist.jsp> 부트스트랩 적용으로 일부 내용만 불러옴!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 <body>
        <!--features_items-->
        <h2 class="title text-center">Features Items</h2>
        <c:forEach items="${emplist}" var="dto">
            <div class="col-sm-4">
                <div class="product-image-wrapper">
                    <div class="single-products">
                        <div class="productinfo text-center">
                            <img class="empimg">
                            <h2>${dto.sal}</h2>
                            <p>${dto.ename}</p>
                            <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
                        </div>
                        <div class="product-overlay">
                            <div class="overlay-content">
                                <h2>$56</h2>
                                <p>Easy Polo Black Edition</p>
                                <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
                            </div>
                        </div>
                    </div>
                    <div class="choose">
                        <ul class="nav nav-pills nav-justified">
                            <li><a href="#"><i class="fa fa-plus-square"></i>Add to wishlist</a></li>
                            <li><a href="#"><i class="fa fa-plus-square"></i>Add to compare</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </c:forEach>
    <!--features_items-->
 </body>
cs

 

<deptlist.jsp> 부트스트랩 적용으로 일부 내용만 불러옴!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 
 <body>
        <!--features_items-->
        <h2 class="title text-center">Features Items</h2>
        <c:forEach items="${deptlist}" var="dto">
            <div class="col-sm-4">
                <div class="product-image-wrapper">
                    <div class="single-products">
                        <div class="productinfo text-center">
                            <img class="empimg">
                            <h2>${dto.dname}</h2>
                            <p>${dto.empVO.ename}</p>
                            <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
                        </div>
                        <div class="product-overlay">
                            <div class="overlay-content">
                                <h2>$56</h2>
                                <p>Easy Polo Black Edition</p>
                                <a href="#" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
                            </div>
                        </div>
                    </div>
                    <div class="choose">
                        <ul class="nav nav-pills nav-justified">
                            <li><a href="#"><i class="fa fa-plus-square"></i>Add to wishlist</a></li>
                            <li><a href="#"><i class="fa fa-plus-square"></i>Add to compare</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </c:forEach>
    <!--features_items-->
 </body>
cs

 

<사원 전체 출력 화면>

 

<부서번호별 출력 화면>