Spring在普通类中使用自动注入Bean
在Spring中,我们会在Controller层使用自动注入的Service层,在Service层使用自动注入的Dao层,如果想在普通的类中使用自动注入Service或者是Dao层时,可以这样做:1、在相应的类上加上@Component注解@Component注解将我们的类实例化到Spring容器中,这样的方式其实就是相当于xml配置文件中的<bean id=""
·
在Spring中,我们会在Controller层使用自动注入的Service层,在Service层使用自动注入的Dao层,如果想在普通的类中使用自动注入Service或者是Dao层时,可以这样做:
1、在相应的类上加上@Component注解
@Component注解将我们的类实例化到Spring容器中,这样的方式其实就是相当于xml配置文件中的
<bean id="" class=""/>这种方式。
2、使用@Autowired注解注入我们需要的Bean
@Autowired是一个自动装配的注解,它会帮你去Spring容器中查找相应的实现。
3、在相应的类中加入一个init()函数,在init()函数中初始化注入的Bean,这个函数上要加上@PostConstruct注解
@PostConstruct注解是Java EE5之后的规范,它是servlet中的一个生命周期环节,被@PostConstruct注解修饰的方法会在构造函数之后就执行。
比如:
@Component public class MybatisTest { @Autowired private ActuatorMapper actuatorMapper; public static MybatisTest mybatisTestUtil; @PostConstruct public void init() { mybatisTestUtil = this; mybatisTestUtil.actuatorMapper = this.actuatorMapper; } public static void insert() { Actuator actuator = new Actuator(); actuator.setId("2312"); mybatisTestUtil.actuatorMapper.insert(actuator); } }
这里的MybatisTest类中就可以直接使用注入的Mapper接口的实现
更多推荐
所有评论(0)