关于java:Spring核心之IOC基础操作篇

55次阅读

共计 9537 个字符,预计需要花费 24 分钟才能阅读完成。

疾速配置

创立我的项目

下载并引入依赖包

下载地址:Spring-5.3.9

官网下载方式参考:官网下载 Spring 的 jar 包教程

编写代码

写一个一般类用作注入的 bean:

package com.hqz;

public class Student {public void study() {System.out.println("I am learning");
    }
}

编写配置文件(配置文件的头部信息是固定的):

<?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="student" class="com.hqz.Student"/>
</beans>

测试类:

package com.hqz;

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

public class Test {public static void main(String[] args) {ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        Student student = applicationContext.getBean("student", Student.class);
        student.study();}
}

最终的我的项目构造如下图所示:

Bean 治理

XML 形式

创建对象

<bean id="dao" class="com.hqz.UserDao"></bean>

三种属性注入形式

set 办法注入

public Class Book {
    private String name;
    
    public void SetName(String name) {this.name = name;}
}
<bean id="book" class="com.hqz.Book">
    <property name="name" value="金瓶梅"></property>
</bean>

有参结构注入

public Class Orders {
    private String name;
    private String address;
    
    public Orders(String name, String address) {
        this.name = name;
        this.address = address;
    }
}
<bean id="orders" class="com.hqz.Orders">
    <!-- 通过属性名称来注入 -->
    <constructor-arg name="name" value="西游记"></constructor-arg>
    <!-- 通过属性索引值来注入 -->
    <constructor-arg index="0" value="中国"></constructor-arg>
</bean>

p 名称空间注入

  1. 第一步:增加 p 名称空间在配置文件中
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       <!-- 增加 p 名称空间在配置文件中 -->
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="user" class="com.hqz.User"/>
</beans>
  1. 第二步:进行属性注入,在 bean 标签外面进行操作
<bean id="book" class="com.hqz.Book" p:name="三国演义"></bean>

各种数据类型注入

注入 null 值

<bean id="book" class="com.hqz.Book">   
    <property name="name">
        <null/>
    </property>
</bean>

注入特殊符号

<bean id="book" class="com.hqz.Book">
    <!-- 谬误写法 -->
    <property name="name" value="<< 南京 >>"></property>
    
    <!-- 正确写法 -->
    <property name="name">
        <value>
            <![CDATA[<< 南京 >>]]>
        </value>
    </property>
</bean>

注入内部 bean

应用 ref 注入

<bean id="userService" class="com.hqz.service.impl.UserServiceImpl">
    <property name="userDao" ref="userDaoImplId" />
</bean>

<bean id="userDaoImplId" class="com.hqz.dao.impl.UserDaoImpl" />

注入外部 bean

<!-- 形式一:外部 bean -->
<bean id="emp" class="com.hqz.bean.Emp">
    <property name="name" value="张三"/>
    <property name="sex" value="女"/>
    <property name="dept">
        <bean id="dept" class="com.hqz.bean.Dept">
            <property name="name" value="技术部"/>
        </bean>
    </property>
</bean>


<!-- 形式二:级联赋值 -->
<bean id="emp" class="com.hqz.bean.Emp">
    <property name="name" value="张三"/>
    <property name="sex" value="女"/>
    <property name="dept" ref="dept" />
</bean>

<bean id="dept" class="com.hqz.bean.Dept">
    <property name="name" value="财务部"/>
</bean>

<!-- 形式三 -->
<bean id="emp" class="com.hqz.bean.Emp">
    <property name="name" value="张三"/>
    <property name="sex" value="女"/>
    <property name="dept" ref="dept"/>
    <property name="dept.name" value="行政部" />
</bean>
<bean id="dept" class="com.hqz.bean.Dept" />
// 部门类
package com.hqz.bean;

public class Dept {
    private String name;

    public String getName() {return name;}

    public void setName(String name) {this.name = name;}
}
// 员工类
package com.hqz.bean;

public class Emp {
    private String name;
    private String sex;

    private Dept dept;

    public Dept getDept() {return dept;}

    public void setDept(Dept dept) {this.dept = dept;}

    public String getName() {return name;}

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

    public String getSex() {return sex;}

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

注入汇合属性

数组类型属性注入
public class Student {private String[] names;

    public void setNames(String[] names) {this.names = names;}
}
<bean id="student" class="com.hqz.Student">
    <property name="names">
        <!-- 数组类型属性注入 -->
        <array>
            <value> 张三 </value>
            <value> 李四 </value>
        </array>
    </property>
</bean>
list 类型属性注入
public class Student {
    private List<String> names;

    public void setNames(List<String> names) {this.names = names;}
}
<bean id="student" class="com.hqz.Student">
    <property name="names">
        <!-- list 类型属性注入 -->
        <list>
            <value> 张三 </value>
            <value> 李四 </value>
        </list>
    </property>
</bean>
map 类型属性注入
public class Student {
    private Map<String, String> maps;

    public void setMaps(Map<String, String> maps) {this.maps = maps;}
}
<bean id="student" class="com.hqz.Student">
    <property name="maps">
        <!-- map 类型属性注入 -->
        <map>
            <entry key="name" value="张三"/>
            <entry key="age" value="20"/>
        </map>
    </property>
</bean>
set 类型属性注入
public class Student {
    private Set<String> sets;

    public void setSets(Set<String> sets) {this.sets = sets;}
}
<bean id="student" class="com.hqz.Student">
    <property name="sets">
        <!-- set 类型属性注入 -->
        <set>
            <value> 李四 </value>
        </set>
    </property>
</bean>

注入对象到汇合中

public class Book {
    private String bookName;

    public void setBookName(String bookName) {this.bookName = bookName;}
}
public class Library {
    private List<Book> bookList;

    public void setBookList(List<Book> bookList) {this.bookList = bookList;}
}
<bean id="book" class="com.hqz.Book">
    <property name="bookName" value="语文" />
</bean>

<bean id="library" class="com.hqz.Library">
    <property name="bookList">
        <list>
            <ref bean="book"></ref>
        </list>
    </property>
</bean>

提取汇合注入

把通用的汇合列表提取进去,不便在多个中央进行援用。

  • 引入 util 命名空间
<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    
</beans>
  • 创立 bean 类
public class Library {
    private List<String> bookList;

    public void setBookList(List<String> bookList) {this.bookList = bookList;}
}
  • 编写配置类
<util:list id="bookListId">
    <value>《三国演义》</value>
    <value>《西游记》</value>
    <value>《水浒传》</value>
    <value>《红楼梦》</value>
</util:list>

<bean id="library" class="com.hqz.Library">
    <property name="bookList" ref="bookListId"/>
</bean>

内部属性文件

  • 引入命名空间

xmlns:context=”http://www.springframework.org/schema/context”

<?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:util="http://www.springframework.org/schema/util"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd 
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
</beans>
  • 编写内部文件

    jdbc.properties

prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/userDb
prop.userName=root
prop.password=root
  • 配置
<!-- 引入内部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>

<!-- 配置连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    <property name="driverClassName" value="${prop.driverClass}"/>
    <property name="url" value="${prop.url}"/>
    <property name="userName" value="${prop.userName}"/>
    <property name="password" value="${prop.password}"/>
</bean>

注解形式

创建对象

  • 配置文件中开启组件扫描
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 开启组件扫描
        1、如果扫描多个名,能够用逗号隔开
        2、或者扫描下层目录
     -->
    <context:component-scan base-package="com.hqz.dao,com.hqz.service"/>
</beans>
  • 增加注解
package com.hqz.service;

import org.springframework.stereotype.Component;

// 在注解外面 value 属性值能够不写
// 默认值是类名称,首字母小写

@Component(value = "userService")
public class UserService {public void add() {System.out.println("中华人民共和国");
    }
}
  • 组件扫描配置
<?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 http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 开启组件扫描
        1、如果扫描多个名,能够用逗号隔开
        2、或者扫描下层目录
     -->
    <context:component-scan base-package="com.hqz.dao,com.hqz.service"/>

    <!-- 示例 1
        use-default-filters="false",示意当初不应用默认 filter,本人配置 filter
        context:include-filter,设置扫描哪些内容
    -->
    <context:component-scan base-package="com.hqz" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 示例 2
        设置哪些内容不扫描
     -->
    <context:component-scan base-package="com.hqz">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

注解阐明

  • @AutoWired:依据属性类型进行主动拆卸
@Service
public class UserService {
    
    @Autowired
    private UserDao userDao;
    
    public void add() {userDao.add();
    }
}
  • @Qualifier:依据属性名称进行注入(比方有多个实现类的接口)
@Service
public class UserService {

    @Autowired
    @Qualifier(value = "userDaoImpl")
    private UserDao userDao;

    public void add() {userDao.add();
    }
}
  • @Resource:能够依据类型注入,也能够依据名称注入
@Service
public class UserService {

    @Resource
    private UserDao userDao;

    public void add() {userDao.add();
    }
}
  • @Value:注入一般类型属性
public class Book {@Value("《金瓶梅》")
    private String bookName;
}

齐全注解开发

  • 创立配置类,代替 xml 配置文件
// 作为配置类,代替 xml
@Configuration
@ComponentScan(basePackages = {"com.hqz"})
public class SpringConfig {}
  • 应用
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);

欢送关注我的公众号:『深海云帆』

正文完
 0