AOP 即面向切面编程 我现在的理解是让对象将关注点仅放在自身所注重上 无视无关自己的事物
就比如说 我播放器正在放歌 我播放器播放歌的时候 并不需要关注这歌一共播放了多少遍 只需要关注放歌这个事件 就可以了
下面就来一一说明 各个文件内容
接口 CompactDisc
public interface CompactDisc {
void playTrack(int k);
}
用于实现CompactDisc接口的BlankDisc类
import java.util.List;
public class BlankDisc implements CompactDisc{
String title;
String artist;
List<String> tracks;
void setTitle(String title){
this.title = title;
}
void setArtist(String artist){
this.artist = artist;
}
void setTracks(List<String> tracks){
this.tracks = tracks;
}
public void playTrack(int k){ //用来播放cd上顺序k的歌曲
System.out.println(tracks.get(k));
}
}
切面类
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect//申明切面
public class TrackCounter {
private Map<Integer,Integer> trackCounters = new HashMap<Integer,Integer>();
@Pointcut( //切点 这样写之后需要每次在位置申明之后加上下面的函数就可以了
"execution(* CompactDisc.playTrack(int) )"+
"&& args(trackNumber) ")
public void trackPlayer(int trackNumber) { }
@Before("trackPlayer(trackNumber)") //Advice 切面该怎么做 这里是记录每首歌播放了几次
public void countTrack(int trackNumber){
int currentCount = getPlayCount(trackNumber);
trackCounters.put(trackNumber,currentCount+1);
System.out.println("歌曲"+trackNumber+"已播放"+(currentCount+1)+"遍");
}
public int getPlayCount(int trackNumber){
return trackCounters.containsKey(trackNumber)?trackCounters.get(trackNumber):0;
}
}
用java配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import java.util.ArrayList;
import java.util.List;
@Configuration//配置申明
@EnableAspectJAutoProxy //自动配置切面申明
public class TrackCountConfig {
@Bean
public CompactDisc seggPeppers(){
BlankDisc cd = new BlankDisc();
cd.setTitle("歌名");
cd.setArtist("歌手");
List<String> tracks = new ArrayList<String> ();
tracks.add("歌曲1");
tracks.add("歌曲2");
tracks.add("歌曲3");
tracks.add("歌曲4");
cd.setTracks(tracks);
return cd;
}
@Bean
public TrackCounter trackCounter(){
return new TrackCounter();
}
}
Test类
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=TrackCountConfig.class)
public class BlankDiscTest {
@Autowired
private CompactDisc cd;
@Autowired
private TrackCounter counter;
@org.junit.Test
public void testTrackCounter() {
cd.playTrack(1);
cd.playTrack(2);
cd.playTrack(3);
}
}
需要注意的是如果要使用AOP 需要加载三个库文件
分别是 aspectj-1.8.13.jar aspectjrt.jar aspectj-weaver.jar
代码都在我的github上~