欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Spring框架学习05引用外部属性文件和基于XML的自动装配

时间:2023-06-11

使用Spring创建数据库连接池,加载外部属性文件dbconfig.properties 

dbconfig.properties 文件配置如下:

jdbc.username=rootjdbc.password=12345678jdbc.jdbcUrl=jdbc:mysql://localhost:3306/testjdbc.driverClass=com.mysql.jdbc.Driver

 加载外部属性文件,引入了classpath类路径下面的dbconfig文件

 基于XML的自动装配

Person类

package com.sf.jin;import java.util.List;import java.util.Map;import java.util.Properties;public class Person { private String name; private Integer age; private String email; private String gender; private Car car; private List bookList; private Map mpas; private Properties properties; public Person() { System.out.println("无参构造器"); } public Person(String name, Integer age, String email, String gender) { System.out.println("有参构造器"); this.name = name; this.age = age; this.email = email; this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } public List getBookList() { return bookList; } public void setBookList(List bookList) { this.bookList = bookList; } public Map getMpas() { return mpas; } public void setMpas(Map mpas) { this.mpas = mpas; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } @Override public String toString() { return "Person{" + "name='" + name + ''' + ", age=" + age + ", email='" + email + ''' + ", gender='" + gender + ''' + ", car=" + car + ", bookList=" + bookList + ", mpas=" + mpas + ", properties=" + properties + '}'; }}

Car类

package com.sf.jin;public class Car { private String carName; private Integer price; private String color; public String getCarName() { return carName; } public void setCarName(String carName) { this.carName = carName; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } @Override public String toString() { return "Car{" + "carName='" + carName + ''' + ", price=" + price + ", color='" + color + ''' + '}'; }}

 给Person赋值Car的值,使用 property:ref 这是手动赋值,使用autowire进行自动装配更方便,

主要有 autowire="byName"根据名字进行装配和  autowire="byType"根据类型进行装配

<?xml version="1.0" encoding="UTF-8"?>

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。