日常技术分享

一、Spring注入方式总结

首先的话有三种注入的方式,分别是:

1.setter方法注入

2.构造注入

3.接口注入,但是接口注入指的是有时我们需要注入来自外界的资源,对Spring框架有侵入,所以一般只用前两种方式。下面对这两种进行总结与归纳。

setter方法注入:指的是我们在一个类中使用set方法为我们的成员属性进行赋值操作,以下展示源代码与操作步骤:

1.建立两个类的Person和Man,在一个包中,目录结构如下:

java spring 接口类中 注入 spring接口注入详解_javaee

Person类、Man类、Test2类:

package entity;

public class Person {

    private String name;//学生的姓名
    private String sex;//学生的性别
    private int age;//学生的年龄
    private Man man;//另一类Man
    //成员属性对应的set方法、构造方法(有参的+无参的)

    public Person( ) {
        System.out.println("Person类的无参构造方法被调用了");
    }
   public Person(String name, String sex, int age, Man man) {
      System.out.println("Person类的有参构造方法被调用了");
      this.name = name;
      this.sex = sex;
      this.age = age;
      this.man = man;
  }

    public void setName(String name) {
        this.name = name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public void setMan(Man man) {
        this.man = man;
    }
    //展示Person类属性的方法
    public void show(){
        System.out.println("name="+name+" "+"sex="+sex+" "+"age="+age+"man="+man);
    }
}

//Man类
package entity;

//男人类
public class Man {
    private String weight;//体重
    private String height;//身高

    //生成成员属性对应的set方法

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    //生成toString方法,方便我们进行输出测试
    @Override
    public String toString() {
        return "Man{" +
                "weight='" + weight + '\'' +
                ", height='" + height + '\'' +
                '}';
    }
}
//测试类Test2类
package test;

import entity.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test2 {
    public static void main(String[] args) {
        //读取配置文件config2.xml
        ApplicationContext context=new ClassPathXmlApplicationContext("config2.xml");
        //获取配置文件中bean,即是Person
        Person person=context.getBean("person",Person.class);
        person.show();
    }
}

config2.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">
       <!--setter方法注入测试-->
      <!--Person类对象创建-->
      <bean id="person" class="entity.Person">
          <!--成员属性name注入-->
          <property name="name" value="金城武"/>
          <!--成员属性sex注入-->
          <property name="sex" value="male"/>
          <!--成员属性age注入-->
          <property name="age" value="46"/>
          <!--成员属性man注入,注意这是一个引用数据类型-->
          <property name="man" ref="mantt"/>
      </bean>

    <!--Man类对象的创建,因为我们要在Person类里面注入此对象-->
    <bean id="mantt" class="entity.Man">
        <!--注意如果我们在Man类中不加对应的属性的set方法的话,这里注入属性时候回报红色的错误的-->
        <!--成员属性weight注入-->
        <property name="weight" value="65kg"/>
        <!--成员属性height注入-->
        <property name="height" value="185cm"/>
    </bean>
</beans>

运行的结果:

java spring 接口类中 注入 spring接口注入详解_spring_02

构造方法注入:指的是我们在一个类中使用有参数的构造方法为我们的成员属性进行赋值操作,以下展示部分源代码与操作步骤:

Person、Man代码与上面一样的,只是配置文件和测试类改一下的:

//Test2测试类
package test;

import entity.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test2 {
    public static void main(String[] args) {
        //读取配置文件config2.xml
//        ApplicationContext context=new //ClassPathXmlApplicationContext("config2.xml");
        //读取配置文件config3.xml
        ApplicationContext context=new ClassPathXmlApplicationContext("config3.xml");
        //获取配置文件中bean,即是Person
        Person person=context.getBean("person",Person.class);
        person.show();
    }
}

config3.xml文件,文件的位置与config2.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">
    <!--使用构造方法注入-->
    <!--Person类对象创建-->
    <bean id="person" class="entity.Person">
        <!--成员属性name注入 -->
       <constructor-arg name="name" value="吴彦祖"/>

        <!--成员属性sex注入-->
        <constructor-arg name="sex" value="male"/>
        <!--成员属性age注入-->
        <constructor-arg name="age" value="44"/>
        <!--成员属性man注入,注意这是一个引用数据类型-->
        <constructor-arg name="man" ref="mantt"/>
        <!--这里的index=0指的是成员属性对应的第一个,读者可以注释掉第一个“吴彦祖”来测试
        <constructor-arg index="0" value="梁朝伟"/>
        index=1,指的是第二个属性,即是sex
         -->

        <!--这个指的是按照成员属性的类型进行构造注入
        <constructor-arg type="java.lang.String" value="元彬"/>
        -->
        
    </bean>

    <!--Man类对象的创建,因为我们要在Person类里面注入此对象-->
    <bean id="mantt" class="entity.Man">
        <!--注意如果我们在Man类中不加对应的属性的set方法的话,这里注入属性时候回报红色的错误的-->
        <!--成员属性weight注入-->
        <property name="weight" value="65kg"/>
        <!--成员属性height注入-->
        <property name="height" value="185cm"/>
    </bean>
</beans>

运行结果:

java spring 接口类中 注入 spring接口注入详解_javaee_03

二、Spring注入类型总结

一般我们使用Spring的IOC容器进行注入时,它可以注入的数据类型如下,除了上面的实例演示的注入类型外,还有一些集合类型的List、Set、Map;下面就演示一下操作的,参考代码如下:

Man、Person、Test2类

//Man类
package entity;

//男人类
public class Man {
    private String weight;//体重
    private String height;//身高

    //生成成员属性对应的set方法

    public void setWeight(String weight) {
        this.weight = weight;
    }

    public void setHeight(String height) {
        this.height = height;
    }

    //生成toString方法,方便我们进行输出测试
    @Override
    public String toString() {
        return "Man{" +
                "weight='" + weight + '\'' +
                ", height='" + height + '\'' +
                '}';
    }
}

//Person类
package entity;

import java.util.*;

public class Person {

    private String name;//学生的姓名
    private String sex;//学生的性别
    private int age;//学生的年龄
    private Man man;//另一类Man
    private List<String> address;//学生的地址
    private List<Double> score;//学生的成绩
    private Set<Integer> id;//学生的学号,是唯一的所以使用Set集合
    private Map<Integer,String> info;//学生的学号对应的姓名,如学号:310------梁朝伟
    //成员属性对应的set方法、构造方法(有参的+无参的)
    public Person( ) {
        System.out.println("Person类的无参构造方法被调用了");
    }

    public Person(String name, String sex, int age, Man man, List<String> address, List<Double> score, Set<Integer> id, Map<Integer, String> info) {
        System.out.println("Person类的有参构造方法被调用了");
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.man = man;
        this.address = address;
        this.score = score;
        this.id = id;
        this.info = info;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public void setMan(Man man) {
        this.man = man;
    }

    public void setAddress(List<String> address) {
        this.address = address;
    }

    public void setScore(List<Double> score) {
        this.score = score;
    }

    public void setId(Set<Integer> id) {
        this.id = id;
    }

    public void setInfo(Map<Integer, String> info) {
        this.info = info;
    }

    //展示Person类属性的方法
    public void show(){
        System.out.println("name="+name+" "+"sex="+sex+" "+"age="+age);
        System.out.println("man="+man);
        System.out.println("address="+ Arrays.asList(address));
        System.out.println("score="+Arrays.asList(score));
        System.out.println("id="+Arrays.asList(id));
        System.out.println("info="+Arrays.asList(info));
    }
}

//Test2类
package test;

import entity.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test2 {
    public static void main(String[] args) {
        //读取配置文件config2.xml
//        ApplicationContext context=new ClassPathXmlApplicationContext("config2.xml");

        //读取配置文件config3.xml
//        ApplicationContext context=new ClassPathXmlApplicationContext("config3.xml");

        //读取配置文件config4.xml
        ApplicationContext context=new ClassPathXmlApplicationContext("config4.xml");
        //获取配置文件中bean,即是Person
        Person person=context.getBean("person",Person.class);
        person.show();
    }
}

config4.xml文件,文件位置同config3.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">
    <!--setter方法注入测试-->
    <!--Person类对象创建-->
    <bean id="person" class="entity.Person">
        <!--成员属性name注入-->
        <property name="name" value="金城武"/>
        <!--成员属性sex注入-->
        <property name="sex" value="male"/>
        <!--成员属性age注入-->
        <property name="age" value="46"/>
        <!--成员属性man注入,注意这是一个引用数据类型-->
        <property name="man" ref="mantt"/>
        <!--成员属性List类型的注入,注意写的格式-->
        <property name="address" >
           <list>
               <value>陕西省安康市旬阳县城关镇</value>
               <value>陕西省安康市旬阳县蜀河镇</value>
               <value>陕西省安康市旬阳县仙河镇</value>
               <value>陕西省安康市旬阳县吕河镇</value>
           </list>
        </property>
        <property name="score" >
            <list>
                <value>98.5</value>
                <value>78.9</value>
                <value>99.9</value>
                <value>66.6</value>
            </list>
        </property>
        <!--成员属性Set类型的注入-->
        <property name="id" >
            <set>
                <value>310</value>
                <value>320</value>
                <value>322</value>
            </set>
        </property>
        <!--成员属性Map类型的注入-->
        <property name="info">
            <map>
                <!--注意这里我们将每一个key和value看成是一个entry-->
                <entry key="310" value="梁朝伟"></entry>
                <entry key="311" value="元彬"></entry>
                <entry key="312" value="刘德华"></entry>
            </map>
        </property>
    </bean>

    <!--Man类对象的创建,因为我们要在Person类里面注入此对象-->
    <bean id="mantt" class="entity.Man">
        <!--注意如果我们在Man类中不加对应的属性的set方法的话,这里注入属性时候回报红色的错误的-->
        <!--成员属性weight注入-->
        <property name="weight" value="65kg"/>
        <!--成员属性height注入-->
        <property name="height" value="185cm"/>
    </bean>
</beans>

运行结果

java spring 接口类中 注入 spring接口注入详解_java spring 接口类中 注入_04

三、Spring常用注解总结

使用位置:类、属性、方法

  • 用在类上面的:@Component、@Controller、@Service、@Repository
    @Component:表示此类是一个通用的容器,当我们在不知道一个类的具体作用的时候,我们就用此注解
    @Controller:表示此类是一个控制器,当我们在知道一个类是充当控制器的角色的时候,即处理来自客户端的请求的时候,我们使用此注解
    @Service:表示的是此类是业务层的组件,用来处理一些业务层的逻辑代码操作,(业务的话,就是用代码对现实世界的一些事情的处理逻辑或是过程进行抽象)
    @Repository:表示的是此类是数据持久化层的组件(DAO 即Data Access Object 数据访问层接口)
  • 用在属性上面的:@Autowired、@Primary、@Qualifier
    @Autowired:表示的是自动注入,一般是按照一个接口的实现类进行注入,默认是按照类型进行注入,即一个接口注入一个实现类的,一般我们使用的是接口进行成员属性的声明。该注解也可以使用在方法上的。
    @Primary:一般指的是,我们一个接口有多个实现类,这是我们就要使用此注解配合@Autowired指明那个是要注入的实现类对象。
    @Primary:用法同上
  • 用在方法上的:@Autowired、@PostMapping、@GetMapping
    @Autowired:用法同上
    @PostMapping:指的是处理post请求的,一般是在controller层的方法中使用
    @GetMapping:指的是处理get请求的,一般是在controller层的方法中使用
    参考代码:(这个代码是之前一个练习项目的部分,所以不能直接运行,读者可以参考这个代码片段,试着自己写一个Demo)
package com.my.web.controller;

import com.my.entity.StudentRegister;
import com.my.service.IStudentInfoRegisterService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;

//学生登记信息提交控制器
@Controller
public class StudentInfoRegisterController {
    @Autowired
     private IStudentInfoRegisterService service;
    @ApiOperation(value="添加学生填报信息",notes="可以重复添加填报信息")
    @PostMapping("/add.do")
    public ModelAndView registerStudentInfo(@ApiParam(value = "学生登记信息对象") StudentRegister info,HttpServletResponse response) throws IOException {
        ModelAndView mv=new ModelAndView();
        //进行学生信息的填报与否判断,有的信息没有填就不进行数据库信息的插入(如:家庭住址)
//        System.out.println("学生的家庭住址:"+info.getAddress().equals(""));
        //打印的是true,如果什么都不提交的话,说明提交的是空字串info.getAddress()时String类型的
        //判断学生登记信息是否填写
        String address=info.getAddress();//学生的地址
        BigDecimal temperature=info.getTemperature();//学生的当前体温
        String previousHistory=info.getPreviousHistory();//学生的既往病史
        String health=info.getHealth();//学生当前的健康情况
        String traffic=info.getTraffic();//学生离校时的交通方式
        String trafficNumber=info.getTrafficNumber();//学生的航班车次
        String otherInfo=info.getOther();//学生的其它情况
        int rows=0;

        //注意处理浏览器显示中文乱码问题
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();

        if("".equals(address)||temperature==null||"".equals(previousHistory)||"".equals(health)||
           "".equals(traffic)||"".equals(trafficNumber)){
            out.print("<script>");
            out.print("alert('------------登记信息没有填写完成,请仔细检查一遍------------');");
            //通过浏览器执行js,完成重定向
            //location代表浏览器的地址栏
            out.print("location='validate.do';");
            //浏览器后退
            out.print("history.back();");
            out.print("</script>");
        }else{
            rows=service.insertStudentRegisterInfo(info);
        }

//        rows=service.insertStudentRegisterInfo(info);
        if(rows==0){
            //成功的话
            mv.setViewName("success");
        }else {
            mv.setViewName("register");
        }
        return mv;
    }
}


//@Service
package com.my.service.impl;

import com.my.dao.IStudentBasicDAO;
import com.my.entity.StudentBasic;
import com.my.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {

    //注入数据访问层接口
    @Autowired
    private IStudentBasicDAO iStudentBasicDAO;
    @Override
    public StudentBasic loginByPhoneNumberAndIdcardNumber(String phoneNumber, String idcardNumber) {
       return iStudentBasicDAO.findByPhoneNumberAndIdCardNo(phoneNumber,idcardNumber);

    }
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements ILoginService {

    //注入数据访问层接口
    @Autowired
    private IStudentBasicDAO iStudentBasicDAO;
    @Override
    public StudentBasic loginByPhoneNumberAndIdcardNumber(String phoneNumber, String idcardNumber) {
       return iStudentBasicDAO.findByPhoneNumberAndIdCardNo(phoneNumber,idcardNumber);

    }
}