Spring6 (1)

1、简介:

自己的理解:spring其实就是一个容器,也可以说是一个框架,主要是控制反转和面向切面编程。
控制反转IOC:是一种思想,就是把new对象的权力交给了spring,也把两个对象之间关系的连接交给了别人。
依赖注入DI:是控制反转的一种实现方式,依赖就是指对象A和对象B之间的关系,注入就是就是一种方式将对象A和对象B关联起来。
依赖注入DI,又包括常见的两种方式:
第一种:set注入(执行set方法给属性赋值)
第二种:构造方法注入(执行构造方法给属性赋值)

注意术语:
OCP:开闭原则(开发原则)
DIP:依赖倒置原则(开发原则)
IoC:控制反转(一种思想,一种新型的设计模式)
DI:依赖注入(控制反转思想的具体实现方式)

2、第一个程序

首先建立一个空项目
在这里插入图片描述
给该项目添加上jdk配置,即给该项目下的所有模块都进行了配置。
在这里插入图片描述
在这里插入图片描述

接着创建一个module模块
在这里插入图片描述
创建一个maven模块
在这里插入图片描述
在resoureces目录下配置spring xml文件配置,即在这里边进行依赖注入。
配置pom.xml(根据自己的需求)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.cky</groupId>
    <artifactId>spring6-demo1</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.1.5</version>
        </dependency>
        <!--log4j2的依赖-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.19.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j2-impl</artifactId>
            <version>2.19.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>


</project>

我的项目目录:
在这里插入图片描述
我的spring6.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="user" class="com.cky.Bean.User"></bean>
    <bean id="userDaoimpl" class="com.cky.dao.impl.UserDaoimpl"></bean>
    <bean id="userServiceimpl" class="com.cky.service.impl.UserServiceimpl">
        <property name="userDao" ref="userDaoimpl"></property>
    </bean>
    <bean id="userweb" class="com.cky.web.Userweb">
        <property name="userService" ref="userServiceimpl"></property>
    </bean>
</beans>

set注入
name是set方法后边的字母(第一个字母小写),ref是要注入bean的id。
set注入是先实例化对象,在注入

构造注入
通过测试得知,通过构造方法注入的时候:
● 可以通过下标 index
● 可以通过参数名 name
● 也可以不指定下标和参数名,可以类型自动推断。
Spring在装配方面做的还是比较健壮的。
构造注入是实例化对象的同时就进行了依赖注入。

2、set注入

2.1 简单数据类型

public static boolean isSimpleValueType(Class<?> type) {
		return (Void.class != type && void.class != type &&
				(ClassUtils.isPrimitiveOrWrapper(type) ||
				Enum.class.isAssignableFrom(type) ||
				CharSequence.class.isAssignableFrom(type) ||
				Number.class.isAssignableFrom(type) ||
				Date.class.isAssignableFrom(type) ||
				Temporal.class.isAssignableFrom(type) ||
				URI.class == type ||
				URL.class == type ||
				Locale.class == type ||
				Class.class == type));
	}

通过源码分析得知,简单类型包括:
● 基本数据类型
● 基本数据类型对应的包装类
● String或其他的CharSequence子类
● Number子类
● Date子类
● Enum子类
● URI
● URL
● Temporal子类
● Locale
● Class
● 另外还包括以上简单值类型对应的数组类型。

2.2测试

package com.cky.Bean;

public class People {
    private String name;

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

    @Override
    public String toString() {
        return "People{" +
                "name='" + name + '\'' +
                '}';
    }
}

package com.cky.Bean;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class User {
    private  Class aClass;
    private String[] names;
    private List<People> peoples;
    private Map<Integer,String> maps;
    private Set<String> sets;
    private String nulls;
    private String email;
    private String p;

    public void setP(String p) {
        this.p = p;
    }

    @Override
    public String toString() {
        return "User{" +
                "aClass=" + aClass +
                ", names=" + Arrays.toString(names) +
                ", peoples=" + peoples +
                ", maps=" + maps +
                ", sets=" + sets +
                ", nulls='" + nulls + '\'' +
                ", email='" + email + '\'' +
                ", p='" + p + '\'' +
                '}';
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setNames(String[] names) {
        this.names = names;
    }

    public void setPeoples(List<People> peoples) {
        this.peoples = peoples;
    }

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

    public void setSets(Set<String> sets) {
        this.sets = sets;
    }

    public void setNulls(String nulls) {
        this.nulls = nulls;
    }

    public void setaClass(Class aClass) {
        this.aClass = aClass;
    }

    public User(){
        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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--    private  Class aClass;
    private String[] names;
    private List<People> peoples;
    private Map<Integer,String> maps;
    private Set<String> sets;
    private String nulls;
        private String email;-->
    <bean name="people1" class="com.cky.Bean.People">
        <property name="name" value="cui"></property>
    </bean>
    <bean name="people2" class="com.cky.Bean.People">
        <property name="name" value="cky"></property>
    </bean>
    <bean name="user" class="com.cky.Bean.User">
<!--     类   -->
        <property name="aClass" value="java.lang.String"></property>
<!--        数组-->
        <property name="names">
            <array>
                <value>a</value>
                <value>b</value>
            </array>
        </property>
<!--        list -->
        <property name="peoples">
            <list>
                <ref bean="people1"></ref>
                <ref bean="people2"></ref>
            </list>
        </property>
<!--        map-->
        <property name="maps">
            <map>
                <entry key="1" value="vui"></entry>
                <entry key="2" value="vui"></entry>
            </map>
        </property>
<!--        set-->
        <property name="sets">
            <set>
                <value>ni</value>
                <value>hao</value>
            </set>
        </property>
<!--        空第一种形式-->
<!--        <property name="nulls" value=""/>-->
<!--        第二种形式-->
        <property name="nulls">
        <value/>
        </property>
<!--        null-->
        <property name="email"><null/></property>
<!--        或者只是不赋值 也为null-->
        <property name="p">
<!--            特殊字符-->
            <value><![CDATA[2 < 3]]></value>
        </property>

    </bean>
</beans>
package com.cky.test;

import com.cky.Bean.User;
import com.cky.web.Userweb;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Mytest {
    @Test
    public void test(){
        //获取spring容器
        ApplicationContext applicationContext= new ClassPathXmlApplicationContext("spring6_1.xml");
        //获取对应的bean
        User userweb = applicationContext.getBean("user", User.class);
        System.out.println(userweb);

    }
}

User{aClass=class java.lang.String, names=[a, b], peoples=[People{name=‘cui’}, People{name=‘cky’}], maps={1=vui, 2=vui}, sets=[ni, hao], nulls=‘’, email=‘null’, p=‘2 < 3’}
在这里插入图片描述

2.3 注入Properties

package com.powernode.spring6.beans;

import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @author 动力节点
 * @version 1.0
 * @className People
 * @since 1.0
 **/
public class People {

    private Properties properties;

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

    @Override
    public String toString() {
        return "People{" +
                "properties=" + properties +
                ", addrs=" + addrs +
                ", phones=" + phones +
                ", names=" + names +
                '}';
    }
}

<?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="peopleBean" class="com.powernode.spring6.beans.People">
        <property name="properties">
            <props>
                <prop key="driver">com.mysql.cj.jdbc.Driver</prop>
                <prop key="url">jdbc:mysql://localhost:3306/spring</prop>
                <prop key="username">root</prop>
                <prop key="password">123456</prop>
            </props>
        </property>
    </bean>
</beans>

2.4 p命名空间注入

本质是set注入,需要提供set方法。

<?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: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="peo" class="com.cky.Bean.People" p:name="cui"></bean>
</beans>

2.5 c命名空间注入

本质是构造注入,需要提供构造方法。

<?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:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--    <bean name="cat" class="com.cky.Bean.Cat" c:_0="k" c:_1="2"></bean>-->
<!--    或者-->
    <bean id="cat" class="com.cky.Bean.Cat" c:name="3" c:age="2"></bean>
    

</beans>

2.6 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">
    <util:properties id="dogbean">
        <prop key="name">k</prop>
        <prop key="age">2</prop>
        <prop key="sex"></prop>
    </util:properties>
    <bean name="dog1" class="com.cky.Bean.Dog">
        <property name="properties" ref="dogbean"></property>
    </bean>
    <bean name="dog2" class="com.cky.Bean.Dog">
        <property name="properties" ref="dogbean"></property>
    </bean>

</beans>

2.6 引入外部配置文件

比如数据源的driver,password,url等配置,我们想要配置到一个jdbc.properties
文件中,然后通过读取该配置文件的值,为我们的类赋值。
DataSource .java

package com.cky.Bean;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.logging.Logger;

public class DataSource implements javax.sql.DataSource {
    private String url;
    private String driver;
    private String password;
    private String username;

    @Override
    public String toString() {
        return "DataSource{" +
                "url='" + url + '\'' +
                ", driver='" + driver + '\'' +
                ", password='" + password + '\'' +
                ", username='" + username + '\'' +
                '}';
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Override
    public Connection getConnection() throws SQLException {
        return null;
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }
}

jdbc.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql//127.0.0.1:3306/spring
username=root
passwoed=123456

spring_pro.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 http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:property-placeholder location="jdbc.properties"></context:property-placeholder>
    <bean id="datasource" class="com.cky.Bean.DataSource">
        <property name="driver" value="${driver}"></property>
        <property name="url" value="${url}"></property>
        <property name="password" value="${passwoed}"></property>
        <property name="username" value="${username}"></property>
    </bean>

</beans>

测试类

   @Test
    public void test4(){
        //获取spring容器
        ApplicationContext applicationContext= new ClassPathXmlApplicationContext("spring_pro.xml");
        DataSource datasource = applicationContext.getBean("datasource", DataSource.class);

        System.out.println(datasource);}

    }

DataSource{url=‘jdbc:mysql//127.0.0.1:3306/spring’, driver=‘com.mysql.cj.jdbc.Driver’, password=‘123456’, username=‘10945’}
注意,这里我们读取到的username是系统的名称,使用 ${} 会让我们先获取到的是 系统变量,所以最好加上前缀。

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql//127.0.0.1:3306/spring
jdbc.username=root
jdbc.passwoed=123456

相关推荐

  1. Spring60Spring WebFlux

    2024-03-28 15:50:03       28 阅读
  2. Spring64Spring框架如何处理异常

    2024-03-28 15:50:03       27 阅读
  3. 60.Spring事务实现基本原理

    2024-03-28 15:50:03       51 阅读
  4. 学习记录691@spring面试之bean的作用域

    2024-03-28 15:50:03       51 阅读
  5. 安卓UI面试题 61-65

    2024-03-28 15:50:03       39 阅读
  6. IOS面试题编程机制 61-65

    2024-03-28 15:50:03       36 阅读
  7. leetcode61-Rotate List

    2024-03-28 15:50:03       30 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-28 15:50:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-28 15:50:03       101 阅读
  3. 在Django里面运行非项目文件

    2024-03-28 15:50:03       82 阅读
  4. Python语言-面向对象

    2024-03-28 15:50:03       91 阅读

热门阅读

  1. python内置函数 V

    2024-03-28 15:50:03       43 阅读
  2. Python:语法糖

    2024-03-28 15:50:03       39 阅读
  3. 本地项目提交到远程服务器的git流程

    2024-03-28 15:50:03       43 阅读
  4. Day32 贪心算法 part02

    2024-03-28 15:50:03       46 阅读
  5. ip地址开发场景问题

    2024-03-28 15:50:03       44 阅读
  6. 安全点安全区的通俗理解

    2024-03-28 15:50:03       41 阅读
  7. Chrome安装Vue插件vue-devtools

    2024-03-28 15:50:03       47 阅读
  8. 学习Dive into Deep learning:2.2 数据预处理,pandas

    2024-03-28 15:50:03       39 阅读
  9. 【晴问算法】算法初步—散列—整数出现次数

    2024-03-28 15:50:03       39 阅读
  10. Linux-跨节点免密登录

    2024-03-28 15:50:03       41 阅读
  11. 2990: 【C3】【递推】蟠桃记

    2024-03-28 15:50:03       42 阅读