解決非controller使用@Autowired注解注入為null問題


在SpringMVC框架中,我們經常要使用@Autowired注解注入Service或者Mapper接口,我們也知道,在controller層中注入service接口,在service層中注入其它的service接口或者mapper接口都是可以的,但是如果我們要在我們自己封裝的Utils工具類中或者非controller普通類中使用@Autowired注解注入Service或者Mapper接口,直接注入是不可能的,因為Utils使用了靜態的方法,我們是無法直接使用非靜態接口的,當我們遇到這樣的問題,我們就要想辦法解決了。
@Autowired注解的方法:

@Component
public class TestUtils {
    @Autowired
    private ItemService itemService;

    @Autowired
    private ItemMapper itemMapper;

    public static TestUtils testUtils;

    @PostConstruct
    public void init() {
        testUtils = this;
    }
}

//utils工具類中使用service和mapper接口的方法例子,用'testUtils.xxx.方法' 就可以了

public static void test(Item record){
    testUtils.itemMapper.insert(record);
    testUtils.itemService.queryAll();
}

如果以上不能解決,只能直接用 dao層:
ApplicationContext context = new ClassPathXmlApplicationContext('classpath:spring/applicationContext-*.xml');
FcglEsHouseMapper sfMapper = context.getBean(FcglEsHouseMapper.class);

然后直接調mybatis接口,不推薦此種,違背springmvc


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM