栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

01Spring的helloworld程序

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

01Spring的helloworld程序

一:Spring的helloworld程序(环境已搭建) 1.导入spring包后,勾选spring配置文件 2.创建Dao.testDao接口,创建它的实现类testDaolmpl,里面有个sayhello方法
package com.Dao;
public interface testDao {
    public void sayhello();
}

package com.Dao;

public class testDaoImpl implements testDao{

    @Override
    public void sayhello() {
        System.out.println("这是一个hello方法");
    }
}
3.配置文件添加如下语句


        

4.测试类

注意:目前有两种参数通过getBean获取对象

    id的方式创建的对象与直接用字节码创建的对象地址是一样的多次在配置文件中用不同的id声明同一个类会报错
package com.Test;

import com.Dao.testDaoImpl;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class test {
    public static void main(String[] args) {
        //激活配置
        ClassPathXmlApplicationContext test = new ClassPathXmlApplicationContext("spring-config.xml");
        
        testDaoImpl testDao = (testDaoImpl) test.getBean("test");
        testDao.sayhello();
        testDaoImpl testDao1 = test.getBean(testDaoImpl.class);
        testDao1.sayhello();
        //进行比较是否为同一地址
        testDaoImpl testDao2 = (testDaoImpl) test.getBean("test");
        System.out.println(testDao==testDao1);
        System.out.println(testDao1==testDao2);
        System.out.println(testDao==testDao2);
        //运行结果
//        这是一个hello方法
//        这是一个hello方法        
//        true
//        true
//        true

    }
}


5.IOC的原理
    测试类:找到构造器ClassPathXmlApplicationContext,解析xml文件xml文件:解析到标签后将class通过反射进行对象创建再保存到内部的容器中。测试类:当测试类使用getBean方法时,从容器中返回这个对象
6.默认参数

注意:在配置文件中声明有参数的对象,实体类必须依赖setget方法

Stdent类

package com.Dao;

public class Student {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + ''' +
                '}';
    }
}

配置文件

        
                
                
        

测试类:

package com.Test;

import com.Dao.Student;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class test01 {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
        Student student = (Student) classPathXmlApplicationContext.getBean("std");
        System.out.println(student.toString());

    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/756478.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号