spring基于注解的 普通类怎么调用(@Services)注解的service方法

public class UserLogUtil {
@Autowired
private static UserLogService userLogService;
/**
* 记录用户日志
* @param userId
* @param toolName
*/
public static void wirteLog(Integer userId,String toolName,String url){
UserLog log = new UserLog();
log.setUserId(userId);
log.setToolName(toolName);
log.setUrl(url.substring(1,url.length()));
userLogService.save(log);
}

}

1、如果你想用@autowired,那么这个类本身也应该是在spring的管理下的,即你的UserLogUtil也要标注为一个component(或Service),这样spring才知道要注入依赖;

2、或者,不标注为component的话,此时不能通过@autowired来注入依赖,只能通过ApplicationContext来取得标注为Service的类:
UserLogService service = ApplicationContext.getBean(UserLogService.class);
温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-01-23
只有把UserLogUtil 类也交给spring管理才能行,调用方法就如你代码所写的,直接注入就好了
第2个回答  2014-01-23
UserLogUtil 类加上一个注解@component
第3个回答  2014-01-23
你用的就对