说明
假设有下面的 Service 类,该类是 其他人写的,并且此人不允许我们改动代码
我们如果想将此类注入到 Controller 中,就需要在该类加上 @Service 注解,但不允许我们改动
创建service类
package top.malaoshi.service;
public class TestService {
public String test(){
return "测试配置类";
}
}
创建配置类
在配置类类名上用
@Configuration注解修饰在方法名上用
@Bean注解修饰,相当于 spring配置文件的<bean>标签,id就是方法名
package top.malaoshi.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.malaoshi.service.TestService;
@Configuration //注解表示配置类,相当于spring框架的applicationContxt.xml配置文件
public class Config {
@Bean //相当于xml配置文件中的<bean>标签。将方法的返回值添加到spring容器中,容器中的id就是方法名
public TestService testService(){
return new TestService();
}
}
创建Controller
使用时,只需要声明成员变量,并用 @Resource 或 @Autowired修饰:
@Resource
private TestService srv;
完整代码:
package top.malaoshi.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import top.malaoshi.service.TestService;
@RestController
public class TestConfigController {
@Resource
private TestService srv; //使用
@GetMapping("/testConfig")
public String test(){
return srv.test();
}
}
执行流程
执行时,首先调用 Config 类的 testService() 方法,将返回值,注入到 TestConfigController 类的 srv 成员变量