Spring 注入

新建dao层接口以及service接口,分别模拟数据层,以及逻辑层代码,其中分别写入一个run()方法:

InjectionInterface.java

package dao.interfaces;

public interface InjectionInterface {

    public void run();

}

ServiceInterface.java

package service.interfaces;

public interface ServiceInterface {
    public void run();
}

新建一个dao层实现类,实现dao层接口方法:
InjectionImpl.java

package dao.interfacesimpl;

import dao.interfaces.InjectionInterface;

public class InjectionImpl implements InjectionInterface {

    @Override
    public void run() {

        System.out.println("Spring Start!");

    }

}

建立一个service层实现类,在其中定义一个私有对象,并可以分别以setter方法,和构造器进行传入,这就是两种注入方法:
ServiceImpl.java

package service.intefacesimpl;

import service.interfaces.ServiceInterface;
import dao.interfaces.InjectionInterface;

public class ServiceImpl implements ServiceInterface {



    private InjectionInterface inject;




    public ServiceImpl(InjectionInterface inject) {
        super();
        this.inject = inject;
    }


    public void setInject(InjectionInterface inject) {
        this.inject = inject;
    }


    @Override
    public void run() {
        System.out.println("Service 业务逻辑!");
        inject.run();
    }

}

新建xml文件,其中加入如下代码:


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd" >

<!--         <bean id="injectionService" class="com.imooc.ioc.injection.service.InjectionServiceImpl"> -->
<!--            <property name="injectionDAO" ref="injectionDAO"></property> -->
<!--         </bean> -->

        <bean id="serviceInterface" class="service.intefacesimpl.ServiceImpl">
            <!-- ><property name="inject" ref="InjectionInterface"></property> -->
            <constructor-arg name="inject" ref="InjectionInterface"></constructor-arg>
        <!-- 此处name一定要和 service.intefacesimpl.ServiceImpl 中的InjectionImpl 参数名一致-->
        </bean>

        <bean id="InjectionInterface" class="dao.interfacesimpl.InjectionImpl"></bean>
</beans>

Bean配置项主要有如下几个:
id:代表唯一标识符
class:具体要实例化的哪一个类
scope:指具体范围,即作用域
Constructor arguments:构造器参数
Properties:设置注入.以上两个方法注入是,name一定要和Service层
的实现类里面参数一致,如上放代码里面的inject.
Autowriting mode:自动装配模式
lazy-initialization mode:懒加载模式
Initialization/destruction method:初始化和销毁的方法。

加载方式:

package test;

import org.junit.After;
import org.junit.Before;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;

public class UnitTestBase {

    private ClassPathXmlApplicationContext context;

    private String springXmlPath;


    public UnitTestBase(){}

    public UnitTestBase(String springXml){
        this.springXmlPath = springXml;
    }

    @Before
    public void before(){
        if(StringUtils.isEmpty(springXmlPath)){
            springXmlPath = "classpath*:spring-*.xml";
        }
        try{
            context = new ClassPathXmlApplicationContext(springXmlPath.split("[,\\s]+"));
            context.start();
        }catch(BeansException e){
            e.printStackTrace();
        }
    }

    @After
    public void after(){
        context.destroy();
    }

    @SuppressWarnings(value = { "unchecked" })
    protected <T extends Object>T getBean(String beanId){
        return (T)context.getBean(beanId);
    }

    protected <T extends Object>T getBean(Class<T> clazz){
        return (T)context.getBean(clazz);
    }
}

通过ClassPathXmlApplicationContext ,实例化一个对象context,然后网其中传入xml文件的路径,调用start()方法,即可启动加载。
然后可以通过context.getBean()方法,可以通过传入的参数生成bean的实例,传入的参数可以是id,也可以是类的类型。

Tips:xml路径填写方式有多种,利用classpath的时候,一般未设置情况下从根目录开始,因此若是将配置文件放在包下,则会报错,书写格式如下:

classpath:com/lds/config/spring-injection.xml

包名之间不是用点,而是用 /

下面是测试代码:

package test;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;

import service.interfaces.ServiceInterface;


@RunWith(BlockJUnit4ClassRunner.class)
public class TestInjection extends UnitTestBase{


    public TestInjection(){
        super("classpath:com/lds/config/spring-injection.xml");
    }


    @Test
    public void testSetter(){
        ServiceInterface interface1 = super.getBean("serviceInterface");
        interface1.run();
    }

    @Test
    public void testConstruct(){
        ServiceInterface interface1 = super.getBean("serviceInterface");
        interface1.run();
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring注入注解是一种在Spring框架中进行依赖注入的方式。通过使用注解,我们可以方便地将依赖对象注入到需要使用它们的类中,从而实现解耦和灵活性。 Spring框架提供了多种注入注解,常用的有: 1. `@Autowired`:自动装配,通过类型进行匹配注入。可以用在构造方法、属性、方法上。当需要注入的对象在容器中有多个实例时,可以结合`@Qualifier`使用。 2. `@Inject`:与@Autowired类似,也是进行自动装配,通过类型进行匹配注入。不过@Inject是Java规范中定义的注解,需要导入`javax.inject`包才能使用。 3. `@Resource`:按名称进行注入。可以通过`name`属性指定要注入的对象名称,也可以通过`type`属性指定要注入的对象类型。 4. `@Value`:用于从配置文件中读取属性值并注入到类的字段中。可以使用`${}`表达式读取配置文件中的值。 5. `@Qualifier`:与@Autowired或@Resource配合使用,通过指定bean的名称来消除自动装配时的歧义性。 6. `@Primary`:与@Autowired或@Resource配合使用,当需要注入的对象在容器中有多个实例时,优先选择带有@Primary注解的实例。 除了上述常用的注入注解,Spring还提供了其他一些注解,如`@Component`、`@Service`、`@Repository`等,用于标识组件、服务、仓库等不同的类,并将其纳入到Spring容器中进行管理。 通过使用这些注解,我们可以在Spring框架中方便地实现依赖注入,提高代码的可读性和可维护性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值