【Spring笔记】Spring创建hello程序

创建Maven工程,配置pom.xml,导入jar包

<?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">
    <parent>
        <artifactId>spring-study</artifactId>
        <groupId>com.kuang</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-01-helloSpring</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

</project>

hello:

 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--bean = 对象-->
    <!--id = 变量名-->
    <!--class = new的对象-->
    <!--property 相当于给对象中的属性设值-->
    <bean id="hello" class="com.kuang.pojo.Hello">
        <property name="str" value="Spring"/>
    </bean>
</beans>

通过bean的方式创建对象。创建一个变量名为hello的Hello对象,设置str的值为Spring

 测试:

 叶子说明由Spring托管

 ●hello对象是由 Spring 创建的。hello对象的属性是由Spring容器设置的。

这个过程就叫控制反转(IOC)

控制:传统应用程序的对象是程序本身控制创建的,使用Spring后,对象是由Spring创建的。

反转:程序本身不创建对象,而变成被动的接收对象

依赖注入:就是利用set方法来进行注入

如果把set去掉,会报错

IOC是一种编程思想,由主动的编程变成被动的接收。要实现不同的操作,只需要在Xml配置文件中进行修改,所谓的IOC,总结的来说就是对象由Spring来创建,管理,装配。

例:使用Spring获取用户数据

 

 如果想要获取其他数据库用户:

只需要修改配置文件中的ref,不需要修改代码

IOC创建对象的方式:

1、使用无参构造函数创建对象(默认)

 

 

 

输出:

默认构造函数
User{name='kuang'} 

2、如果使用有参构造函数创建对象:

方法一:使用construtor-arg index

 

 

 测试

 输出:

User{name='kuang'}

方式二:参数类型(不建议使用)

 如果两个参数相同,则不能使用

方式三:直接通过参数名(推荐使用)

Spring容器在getBean之前,就已经把类实例化了。内存中只有一个实例。


 

猜你喜欢

转载自blog.csdn.net/m0_52043808/article/details/124374831