非controller类调用spring框架的service

1、在使用spring-mvc框架的时候经常会遇到在非controller类里面调用service方法,service类使用的是注解,如果直接调用的话会出现service为null

private static UserAppService service;// 用户服务类

@Autowired
public void setService(UserAppService service) {
    GoalControlRule.service = service;
}

注方法类型加:@Component注解
例如:

  @Component
public class GoalControlRule {
   private static UserAppService service;// 用户服务类
    @Autowired
    public void setService(UserAppService service) {
        GoalControlRule.service = service;
    }
    private static BasicArchivesPlatformService basicArchivesPlatformService;//基础档案平台服务类
    @Autowired
    public void setBasicArchivesPlatformService(BasicArchivesPlatformService basicArchivesPlatformService) {
        GoalControlRule.basicArchivesPlatformService = basicArchivesPlatformService;
    }
}
2、main方法中调用spring持久层service或dao

private  static  ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
private  static  UserPlatformService userPlatformService = (UserPlatformService) ac.getBean("userPlatformService");
public static void main(String[] args) {
    System.out.println(userPlatformService.getPatientInfo("2489"));
}

你可能感兴趣的:(Spring,JAVA)