木舟0基础学习Java的第二十九天(Spring,Spring的属性注入(xml,注解))

Spring(Spring FrameWork)

Spring是一个开源框架,最早由Rod Johnson发起 Spring为简化企业级开发而生 使用Spring开发可以将Bean对象交给Spring容器来管理 这样使得很多复杂的代码在Spring中开发会变得优雅简洁 有效的降低代码的耦合度 极大的方便项目的后期维护 升级 和扩展

官网:Https://spring.io

概述:

Spring是一个轻量级控制反转(IOC)和面向切面(AOP)为核心的容器框架

正转

|-------------|---------|--------------|-------|----------|
| Person.java | javac → | Person.class | new → | Person对象 |

第一个Spring程序(IOC案例)
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
        https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--下面这句话等同于 Users user=new User();告诉Spring这个com.spring.pojo.Users类交给你管理了-->
 <bean id="user" class="com.spring.pojo.Users"></bean>

</beans>
java 复制代码
@Data
public class Users implements Serializable {
    private int id;
    private String uname;
    private String pwd;
}
java 复制代码
public class Demo {
    //控制正转的方式
    @Test
    public void run1(){
        Users user = new Users();
        user.setId(1);
        user.setUname("张三");
        user.setPwd("333");
        System.out.println(user);
    }
    //Spring中的控制反转技术(简称IOC技术)
    @Test
    public void run2(){
        //加载spring.xml配置文件
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
        //通过id从spring容器的对象缓存池中取bean(Users)对象
        //ac.getBean("user");//这时对象会被自动提升为Object对象 需要强转回来
        Users user =(Users) ac.getBean("user");
        user.setId(1);
        user.setUname("妮妮");
        user.setPwd("0105");
        System.out.println(user);
    }
}

基于xml映射文件中 bean标签的属性注入

java 复制代码
@Data
public class Users implements Serializable {
    private int id;
    private String uname;
    private String pwd;

    //持有Clazz 引用数据类型
    private Clazz clazz;

    private Account account;
}
java 复制代码
public class Clazz implements Serializable {
private String cname;
private int room;

    public Clazz() {
    }

    public Clazz(String cname, int room) {
        this.cname = cname;
        this.room = room;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public int getRoom() {
        return room;
    }

    public void setRoom(int room) {
        this.room = room;
    }

    @Override
    public String toString() {
        return "Clazz{" +
                "cname='" + cname + '\'' +
                ", room=" + room +
                '}';
    }
}
java 复制代码
/*其他数据类型的注入*/
public class Data implements Serializable {
    private String[] arr;
    private List<Integer> list;
    private Set set;
    private Map map;
    private Properties properties;

    public Data() {
    }

    public Data(String[] arr, Properties properties, Map map, Set set, List<Integer> list) {
        this.arr = arr;
        this.properties = properties;
        this.map = map;
        this.set = set;
        this.list = list;
    }

    public String[] getArr() {
        return arr;
    }

    public void setArr(String[] arr) {
        this.arr = arr;
    }

    public List<Integer> getList() {
        return list;
    }

    public void setList(List<Integer> list) {
        this.list = list;
    }

    public Set getSet() {
        return set;
    }

    public void setSet(Set set) {
        this.set = set;
    }

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    @Override
    public String toString() {
        return "Data{" +
                "arr=" + Arrays.toString(arr) +
                ", list=" + list +
                ", set=" + set +
                ", map=" + map +
                ", properties=" + properties +
                '}';
    }
}
java 复制代码
/*账户*/
public class Account {
    private int aid;
    private long money;

    public Account() {
    }

    public Account(int aid, long money) {
        this.aid = aid;
        this.money = money;
    }

    public int getAid() {
        return aid;
    }

    public void setAid(int aid) {
        this.aid = aid;
    }

    public long getMoney() {
        return money;
    }

    public void setMoney(long money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "aid=" + aid +
                ", money=" + money +
                '}';
    }
}
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
        https://www.springframework.org/schema/beans/spring-beans.xsd"
 default-autowire="byName"
>
<!--全局自动注入↑  下面的每个bean都会自动注入-->

<!--下面这句话等同于 Users user=new User();告诉Spring这个com.spring.pojo.Users类交给你管理了-->
 <bean id="user" class="com.spring.pojo.Users" scope="prototype">
  <!--scope="singleton"单态模式 默认是这个 从bean取出的对象为 同一 对象-->
  <!--scope="prototype"原型模式 从bean取出的对象为 不同 对象-->
  <!--这个标签不仅可以声明类 也可以给该类赋值-->
  <property name="id" value="1"></property>
  <property name="uname" value="小依"></property><!--等同于user.setUname("小依");-->
  <property name="pwd" value="111"></property>
 </bean>
<!--通过set方法给属性注入值-->
 <bean id="clazz" class="com.spring.pojo.Clazz">
  <property name="cname" value="计算机应用科学"></property>
  <property name="room" value="101"></property>
 </bean>
 <!--通过构造方法给属性注入值
     相当于new Clazz("英语",201)-->
<bean id="claz" class="com.spring.pojo.Clazz">
 <constructor-arg name="cname" value="英语"></constructor-arg>
 <constructor-arg name="room" value="201"></constructor-arg>
</bean>
<!--给引用数据类型 持有的Clazz注入值-->
 <bean id="user2" class="com.spring.pojo.Users" scope="prototype">
  <!--scope="singleton"单态模式 默认是这个 从bean取出的对象为 同一 对象-->
  <!--scope="prototype"原型模式 从bean取出的对象为 不同 对象-->
  <!--这个标签不仅可以声明类 也可以给该类赋值-->
  <property name="id" value="2"></property>
  <property name="uname" value="小贰"></property>
  <property name="pwd"><value/></property><!--<value/>或者<null/>空值注入-->
  <property name="clazz" ref="clazz"></property><!--ref="clazz"关联clazz-->
 </bean>

 <bean id="data" class="com.spring.pojo.Data">
  <property name="arr">
   <array>
    <value>北京</value>
    <value>上海</value>
    <value>广州</value>
    <value>深圳</value>
   </array>
  </property>
  <property name="list">
   <list>
    <value>10</value>
    <value>20</value>
    <value>30</value>
    <value>40</value>
   </list>
  </property>
  <property name="set">
   <set>
    <value>庐山</value>
    <value>衡山</value>
    <value>华山</value>
    <value>庐山</value>
   </set>
  </property>
  <property name="map">
   <map>
    <entry key="北京" value="010"></entry>
    <entry key="广州" value="021"></entry>
    <entry key="上海" value="020"></entry>
   </map>
  </property>
  <property name="properties">
   <props>
    <prop key="省会">奉天</prop>
    <prop key="菜品">烧烤</prop>
    <prop key="特色">洗浴</prop>
   </props>
  </property>
 </bean>
<!--局部自动注入-->
 <bean id="account" class="com.spring.pojo.Account">
  <property name="aid" value="11"></property>
  <property name="money" value="12000"></property>
 </bean>
 <bean id="user3" class="com.spring.pojo.Users" scope="prototype" autowire="byType">
  <!--autowire=""自动注入-->
  <!--autowire="byName"根据名字account自动注入 名字对应Users中持有的名称private Account account;-->
  <!--autowire="byType"根据类型com.spring.pojo.Account自动注入 注意:不能同时有两个com.spring.pojo.Account-->
  <property name="id" value="3"></property>
  <property name="uname" value="小山"></property>
  <property name="pwd" value="333"></property>
  <property name="clazz" ref="clazz"></property><!--ref="clazz"关联clazz-->
 </bean>
</beans>

基于注解的注入

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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- bean definitions here -->
    <!--以下的标签是在当前文件被加载之后,扫描指定的包下所有的实体类-->
    <context:component-scan base-package="com.spring.pojo"></context:component-scan>

</beans>
java 复制代码
@Component/*这个注解是告诉spring容器,当你扫描com.spring.pojo包下所有的实体类时
捕捉该@Component注解 将含有这个注解的类 加载到容器中 并创建对象。。。*/
/*该注解相当于 Users users=new Users(); 当前并没有指定该类名称 默认首字母小写为该类名称 users*/
/*@Component("u") 指定该类名称为u*/
//@Scope("singleton")//默认 指定该类为单例模式
@Scope("prototype")//指定该类为多例(原形)模式
public class Users implements Serializable {
    @Value("2")
    private int id;
    @Value("小贰")//给uname 赋值
    private String uname;
    @Value("222")
    private String pwd;

    //@Resource//引用类型的数据 根据bean的类型自动注入
    @Autowired//自动注入 同@Resource一样 建议使用
    private Clazz clazz;
    //@Qualifier//声明注入 根据指定的bean的名字自动注入 要与@Autowired搭配使用 建议不用
    @Resource//引用类型的数据 根据其类型自动注入
    private Account account;

    public Users() {
    }

    public Users(int id, String uname, String pwd, Clazz clazz, Account account) {
        this.id = id;
        this.uname = uname;
        this.pwd = pwd;
        this.clazz = clazz;
        this.account = account;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    public Clazz getClazz() {
        return clazz;
    }

    public void setClazz(Clazz clazz) {
        this.clazz = clazz;
    }

    public Account getAccount() {
        return account;
    }

    public void setAccount(Account account) {
        this.account = account;
    }

    @Override
    public String toString() {
        return "Users{" +
                "id=" + id +
                ", uname='" + uname + '\'' +
                ", pwd='" + pwd + '\'' +
                ", clazz=" + clazz +
                ", account=" + account +
                '}';
    }
}
java 复制代码
/*账户*/
@Component(value = "account")//括号内的value可以省略
public class Account {
    @Value("101")
    private int aid;
    @Value("12000")
    private long money;

    public Account() {
    }

    public Account(int aid, long money) {
        this.aid = aid;
        this.money = money;
    }

    public int getAid() {
        return aid;
    }

    public void setAid(int aid) {
        this.aid = aid;
    }

    public long getMoney() {
        return money;
    }

    public void setMoney(long money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "aid=" + aid +
                ", money=" + money +
                '}';
    }
}
java 复制代码
public class Demo {
    @Test
    public void run1(){
       ApplicationContext ca = new ClassPathXmlApplicationContext("Spring.xml");
        Users users =(Users) ca.getBean("users");
        users.setId(1);
        users.setUname("小依");
        users.setPwd("111");
        users.setClazz(new Clazz("计算机",101));
        users.setAccount(new Account(1,12000));
        System.out.println(users);
    }
    @Test
    public void run2(){
        ApplicationContext ca = new ClassPathXmlApplicationContext("Spring.xml");
        Users users =(Users) ca.getBean("users");
        System.out.println(users);
    }
}

Spring的IOC(注解)

**@Component:**表示当前修饰的类交给Spring容器管理 修饰一个类 将其交给Spring容器

与@Component相同功能的 还有三个衍生注解 都是用来修饰类:

**@Repository:**添加在mapper的接口类上(数据访问层)

**@Service:**添加在Service实现类上(业务层)

**@Controller:**添加在Controller类上(控制层)

**@Configration:**添加在用于配置信息的类上(SpringBoot中自动配置)

使用场景:

**XML:**可以使用在任何场景 开发中用来注入框架实例 基于xml操作的是.class文件

**注解:**有些地方用不了 比如这个类不是自己写的(注解必须写在源代码上) 开发中用来注入自己写的Java类 基于注解操作的是源代码

相关推荐
面试鸭13 分钟前
第一次见到要主动降薪的。。。
java·学习·面试·职场和发展
羊羊一洋13 分钟前
线性代数学习笔记~
笔记·学习
计算机学姐22 分钟前
基于微信小程序的剧本杀游玩一体化平台
java·vue.js·spring boot·微信小程序·小程序·intellij-idea·mybatis
IT学长编程1 小时前
计算机毕业设计 美发管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·毕业论文·计算机毕业设计选题·计算机毕业设计开题报告·美发管理系统
2407-2 shw1 小时前
Tomcat CVE-2017-12615 靶场攻略
java·tomcat
向上爬的卓卓卓2 小时前
C++【类和对象】(构造函数与析构函数)
java·开发语言·c++·visual studio
朝九晚五ฺ2 小时前
【Linux探索学习】第一弹——Linux的基本指令(上)——开启Linux学习第一篇
linux·运维·学习
战神刘玉栋2 小时前
《程序猿之设计模式实战 · 适配器模式》
数据库·设计模式·适配器模式
AI-入门2 小时前
【LangChain系列】实战案例5:用LangChain实现灵活的Agents+RAG,该查时查,不该查时就别查
数据库·人工智能·深度学习·面试·职场和发展·langchain
动物园首领2 小时前
Java 中创建线程几种方式
java·java创建线程方式