美文网首页
Hello Spring

Hello Spring

作者: 极速奔跑的蛋蛋 | 来源:发表于2022-10-18 14:45 被阅读0次

    引入webmvc支持,在项目的pom.xml文件中

    <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>5.3.23</version>
            </dependency>
        </dependencies>
    

    创建HelloSpring的dao类

    public class Hello {
        private String hello;
    
        public String getHello() {
            return hello;
        }
    
        public void setHello(String hello) {
            this.hello = hello;
        }
    
        @Override
        public String toString() {
            return "Hello{" +
                    "hello='" + hello + '\'' +
                    '}';
        }
    }
    

    在resources层级下创建配置文件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">
    
    <!--    使用spring创建对象(无参)-->
        <bean id="helloSpring" class="com.test.demo.Hello">
            <property name="hello" value="spring"/>
        </bean>
    <!--    有参-->
        <bean id="helloSpring" class="com.wyk.demo.Hello">
            <constructor-arg name="name" value="你好"/>
        </bean>
    </beans>
    <!--   id:相当于变量名;class:指定具体类 (等同于 Hello 变量名 = new Hello() ) -->
    <!--  property 相当于给对象中的属性进行赋值,给hello这个属性赋值spring -->
    <!--  constructor-arg name(通过名称进行赋值)、index(通过下标赋值)、type(通过类型赋值,不推荐) -->
    

    最后编写test类.这里需要使用ClassPathXmlApplicationContext进行获取配置文件,ClassPathXmlApplicationContext继承自ApplicationContext(并非直接继承,中间还有多个继承关系,主要是处理各种配置文件的ApplicationContext).

     public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            // 通过getBean()获取对象
            Hello hello = (Hello) context.getBean("helloSpring");
            System.out.println(hello.toString());
        }
    }
    
    // 输出(无参)
    Hello{hello='spring'}
    // 输出(有参)
    Hello{hello='你好'}
    

    如何去理解这部分代码,我的想法是这里做了一个反序列化操作.从而获取对象进行一些列操作。

    import使用:在多人开发中使用,大家可以各自编写xml文件,在ApplicationContext.xml中使用import进行引用

     <import resource="beans.xml"/>
     <import resource="beans2.xml"/>
    

    这样只需加载ApplicationContext.xml文件,便可以随意使用其他xml文件。

    ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
     // 通过getBean()获取对象
    Hello hello = (Hello) context.getBean("helloSpring2");
    System.out.println(hello.toString());
    

    相关文章

      网友评论

          本文标题:Hello Spring

          本文链接:https://www.haomeiwen.com/subject/ruajzrtx.html