中Bean的自动注入
我们在使用Springboot时,最为常用的bean的注入方式莫过于自动注入了吧,通过在springboot项目中加各种注解即
可使用自动注入,步骤(相对简洁,不过很粗暴)demo如下:
- 启动类上加@SpringBootApplication
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application .class, args);
}
}
- Controller类上加@RestController
//controller层
@RestController
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/test")
public String testDemo(String talk){
return testService.talk(talk);
}
}
- Service接口类上加@Service
//service层
public interface TestService {
String talk(String talk);
}
//serviceImpl
@Service
public class TestServiceImpl implements TestService {
@Resource
private TestMapper testMapper;
@Override
public String talk(String talk){
return testMapper.talk();
}
}
- Mapper类上加@Mapper(启动类上加@MapperScan(basePackages = {“mapper文件所在的路径”})也行)
//持久层
@Mapper
public interface TestMapper {
String talk(@Param("talk") String talk);
}
当然再牛叉的技术都是不会十全十美的,当你引用一些其他技术到项目中时,有些可能会导致自动注入出现注入失败的情况,
这时候就延申到我们第二种方式啦
中Bean的非自动注入
2.1 首先创建一个SpringContextHolder类,放入到项目中
@Component
@SuppressWarnings("all")
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public SpringContextHolder() {
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
assertApplicationContext();
return applicationContext;
}
public static <T> T getBean(String beanName) {
assertApplicationContext();
return (T) applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> requiredType) {
assertApplicationContext();
return applicationContext.getBean(requiredType);
}
public static <T> List<T> getBeanOfType(Class<T> requiredType) {
assertApplicationContext();
Map<String, T> map = applicationContext.getBeansOfType(requiredType);
return map == null ? null : new ArrayList(map.values());
}
public static void autowireBean(Object bean) {
applicationContext.getAutowireCapableBeanFactory().autowireBean(bean);
}
private static void assertApplicationContext() {
if (applicationContext == null) {
throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");
}
}
}
2.2在实体类中给主键字段添加注解
@Data
public class Test{
@TableId(type = IdType.AUTO)
private Integer id;
private String talk;
}
2.3在使用对应的bean的时候,用一下代码进行创建
//获取Service
TestService testService = SpringContextHolder.getBean(TestService.class);
//获取Mapper
TestMapper testMapper = SpringContextHolder.getBean(TestMapper.class);
到此,我们就已经可以使用我们想要的Bean啦,原理什么的,我看着也很烦,就不在这里说了,CV大法帮助你,哈哈
PS: 内容较为简介,不过稍微一看就能看懂啦,小伙伴们加油哦