SpringBoot默认会扫描启动类当前的包以及子包,那对于没有在这些包下的类,该怎么注册到IOC容器中呢?
可以使用@Import注解来注册。
@Import具体用法如下:
项目结构如下:
TestController类中需要用到Test1Service, 而启动类未com.gm.test1包中的Application,Test1Service位于com.gm.test2.service包中,如果直接在Test1Service上加@Service注解,SpringBoot根本不会扫描到。
1 创建com.gm.test1.configure包,在该包中创建TestServiceConfig类,该类的内容如下:
package com.gm.test1.configure;
import com.gm.test2.service.Test1Service;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import(Test1Service.class)
public class TestServiceConfig {
}
PS:之所以加上@Configuration注解,是为了让SpringBoot能够扫描到,扫描到之后,SpringBoot会为@Import中的类创建实例,并注册到IOC容器中
2 在TestConroller可以直接通过@Autowire注解来注入Test1Service实例,代码如下:
package com.gm.test1.controller;
import com.gm.test2.service.ITestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
@Autowired
private ITestService testService;
@GetMapping("/test")
public String test() {
logger.info("<test> start");
testService.say("Jim", "Hello");
return "OK";
}
}
3 ITestService内容如下:
package com.gm.test2.service;
public interface ITestService {
void say(String name, String info);
}
4 Test1Service内容如下:
package com.gm.test2.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Test1Service implements ITestService {
private static final Logger logger = LoggerFactory.getLogger(Test1Service.class);
@Override
public void say(String name, String info) {
logger.info("<say> " + name + " say: " + info);
}
}