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

Spring的Xml配置

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

Spring的Xml配置

文章目录
  • spring的Xml配置
    • 基本配置
    • 单例及多例
    • 构造方法赋值
    • 引用外部文件 properties

spring的Xml配置 基本配置

首先 maven项目中导入架包


            org.springframework
            spring-context
            5.3.19


            org.projectlombok
            lombok
            1.18.24

创建一个实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
    private String name;
    private int age;
}

在resource目录下创建spring配置文件 applicationContext.xml




    
    

创建测试方法对其进行测试

  @Test
    public void test1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user1 = (User) applicationContext.getBean("user1");
        System.out.println("user1 = " + user1);
    }

运行之后输出结果: user1 = User(name=null, age=0)

赋值

修改 applicationContext.xml文件,对实体类进行赋值


        
        

运行之后输出结果: user1 = User(name=张三, age=18)

单例及多例

单例模式,故名思意。在一个配置项中有且只能创建一个实体类对象。其在 new ClassPathXmlApplicationContext(“applicationContext.xml”) 时就已经生成实体类对象。而多例需要在applicationContext.getBean(“user1”) 时创建。

单例


        
        

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
User user1 = (User) applicationContext.getBean("user1");
System.out.println("user1 = " + user1);

运行之后输出结果: user1 = User(name=张三, age=18)

多例

    
        
        
    
    
        
        
    
    @Test
    public void test1() {
        ApplicationContext applicationContext = new 	ClassPathXmlApplicationContext("applicationContext.xml");
        User user1 = (User) applicationContext.getBean("user1");
        System.out.println("user1 = " + user1);
        User user2 = (User) applicationContext.getBean("user2");
        System.out.println("user2 = " + user2);
    }

运行之后输出结果:

​ user1 = User(name=张三, age=18)
​ user2 = User(name=李四, age=19)

  • bean:通过配置bean将实体类对象交给Spring容器
  • id:给被管理的对象命名
  • class:被管理对象的全限定名
  • scope(进阶):默认singleton即为单利模式,就是在Spring容器中只存在一个的实例。
  • property:通过Set方法进行依赖注入
  • 依赖注入常用的两种:1.set方法注入。2.构造函数注入。
  • 另外两种(了解)p命名和c命名空间注入:不能直接使用,需导入xml约束。
构造方法赋值

修改 applicationContext.xml


        
        

 @Test
    public void test1() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        User user1 = (User) applicationContext.getBean("user1");
        System.out.println("user1 = " + user1);
    }

运行之后输出结果: user1 = User(name=张三, age=18)

引用外部文件 properties

创建properties文件 jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc://192.168.1.10:3306/test
jdbc.username=root
jdbc.password=root

修改applicationContext.xml




    
    
        
        
        
        
    



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

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

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