Proguard混淆代码导致Spring自动装配失败

最近尝试用Proguard来混淆代码,以增加发布出去的代码安全性。今天运行混淆后的jar包发生如下异常

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: public abc.service.Service test.rest.controller.Controller.service; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [abc.service.Service] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 26 more

 

程序很简单,接口

 

Java代码   收藏代码
  1. public interface Service {  
  2.     int getAge();  
  3. }  

 实现类使用@Component标签实例化到spring容器中

 

 

Java代码   收藏代码
  1. @Component  
  2. public class ServiceImpl implements Service{  
  3.     public int getAge() {  
  4.         return new Random().nextInt(100);  
  5.     }  
  6. }  

 在Controller中使用@Autowired标签自动装配

 

 

Java代码   收藏代码
  1. @Autowired  
  2. public Service service;  

 

 

原程序可以正常运行,但在混淆了代码之后,发生以上所述的异常,原因是spring找不到能够匹配的Service实例。

 

忙活了一整天各种测试各种查资料,终于找到解决方案,很简单

 

1.在proguard配置中加上“-keepdirectories”

2.保证proguard版本不低于4.4

 

另外附上解决前和解决后的jar包解压时候的控制台输出

 

1.这是没加“-keepdirectories”的输出

inflated: META-INF/MANIFEST.MF
inflated: abc/service/Service.class
inflated: test/rest/controller/Controller.class
inflated: test/rest/controller/ServiceImpl.class
inflated: META-INF/maven/test/rest/pom.xml
inflated: META-INF/maven/test/rest/pom.properties

 

2.加上“-keepdirectories”之后解压

created: META-INF/
inflated: META-INF/MANIFEST.MF
created: abc/
created: abc/service/
created: test/
created: test/rest/
created: test/rest/controller/
inflated: abc/service/Service.class
inflated: test/rest/controller/Controller.class
inflated: test/rest/controller/ServiceImpl.class
created: META-INF/maven/
created: META-INF/maven/test/
created: META-INF/maven/test/rest/
inflated: META-INF/maven/test/rest/pom.xml
inflated: META-INF/maven/test/rest/pom.properties


转自:http://kane-xie.iteye.com/blog/2240340

你可能感兴趣的:(spring,Proguard)