在SMM项目中,经常使用@Autowired引入service或者mapper,但是在自定的utils包下引入service或者mapper的时候,会出现null的情况,下面就来解决这个问题。
首先,我们在spring的配置文件application.xml中加上 扫描utils工具类的配置
使用@value注解赋值,需要将值写入properties文件中。切记:我们需要将这个properties文件的扫描配置写入 application.xml文件中,不能放入springmvc.xml文件中,因为:
1、tomcat启动一个WEB项目的时候,WEB容器会去读取它的配置文件web.xml。applicationContext.xml是随ContextLoaderListener的加载而执行的,而springmvc.xml是随DispatcherServlet的加载而执行的,在web.xml中;
2、加载顺序是listener>filter>servlet;
3、applicationContext.xml先加载!
<context:component-scan base-package="com.ocean.service,com.ocean.utils">
</context:component-scan>
<context:property-placeholder location="classpath:*.properties" />
接下来在就是在这个工具类中的实现了,需要使用 @PostConstruct注解。
@PostConstruct注解的方法将会在依赖注入完成后被自动调用,指的是在项目启动的时候执行这个方法,也可以理解为在spring容器启动的时候执行
@Component
public class SearchNoUtils {
@Autowired
private static StdNewSeachService stdNewSeachService;
private static SearchNoUtils searchNoUtils;
private static String url;
@Value(value="${STD_FILE_URL}")
public void setUrl(String url) {
SearchNoUtils.url = url;
}
public String getUrl() {
return url;
}
@PostConstruct
public void init() {
searchNoUtils = this;
}
public StringBuffer makeNo(){
//业务逻辑的处理
searchNoUtils.stdNewSeachService.findXXX();
System.out.println(searchNoUtils.url);
//....
}
}