友情提示:aop不能代理静态方法,不能代理工具类中的静态方法,但是最有病的就是你如果强行写代理静态方法他还不报错!!!还正经执行但是没进aop
最近再写一个爬虫的项目,我希望项目启动之后就开始执行我的启动方法,所以我给方法加了@PostConstruct注解,让项目启动之后就开始执行。注意哈,这个注解作用在方法,这个类一定是可以被扫描的,我加了一个@service,应该@compent应该也可以。
@Service
public class ThreadRunDemo {
private static Map<String,Thread> threadMap = new HashMap();
@PostConstruct
public static void aaa() {
System.out.println("多线程启动");
GetJedisThread getJedisThread = new GetJedisThread();
Thread t1 = new Thread(new GetJedisThread());
Thread t2 = new Thread(new GetJedisThread());
Thread t3 = new Thread(new GetJedisThread());
threadMap.put(t1.getName(),t1);
threadMap.put(t2.getName(),t2);
threadMap.put(t3.getName(),t3);
/*DataUrlThreadTest dataUrlThreadTest = new DataUrlThreadTest();
Thread thread1 = new Thread(dataUrlThreadTest);
threadMap.put(thread1.getName(),thread1);*/
Thread thread = new Thread(new DaemoThreadTest(threadMap));
thread.start();
t1.start();
t2.start();
t3.start();
//thread1.start();
}
}
那么情况就来了,因为在线程里我用到了一些工具类,这个工具类我是想放在ioc里的,然后用cglib实现以下aop监测,但是如果项目启动后直接启动线程开始方法我发现我cglib中的配置并没有执行,如果我在启动方法打上断点等一会则又执行了,我怀疑是启动后直接加载这个时候工具类还没被加载,所以才这样的。
@Override
public void run() {
JedisPoolUtils proxyObject = ProxyUtils.createProxyObject(JedisPoolUtils.class);
this.jedis = proxyObject.getPublicJedis();
//给jedis赋值
}
JedisPoolUtils 是我自己写的,就是个cglib的工具类,因为我么的接口,所以cglib,没被加载的话我只能让我的线程晚点执行,我就得让它等一会。
对不起,我失败了,但是我找到了别的方法
@Service
public class ThreadRunDemo implements ApplicationRunner {
private static Map<String,Thread> threadMap = new HashMap();
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("多线程启动");
GetJedisThread getJedisThread = new GetJedisThread();
Thread t1 = new Thread(new GetJedisThread());
Thread t2 = new Thread(new GetJedisThread());
Thread t3 = new Thread(new GetJedisThread());
threadMap.put(t1.getName(),t1);
threadMap.put(t2.getName(),t2);
threadMap.put(t3.getName(),t3);
Thread thread = new Thread(new DaemoThreadTest(threadMap));
thread.start();
t1.start();
t2.start();
t3.start();
}
}
继承ApplicationRunner接口,重写run方法,它就会在你的ioc啥的加载完成之后执行的,对不起,让大家失望了,但是我这是给自己看的,自己不失望就好,吼吼吼!