用idea初学Spring5于哔哩哔哩狂神说java.留笔记便于以后查找.
此处重点有三:
- 用构造函数赋值的bean
- 起别名
- 将所有的bean导入一个总表中.
1. 创建实体类
User.class
package com.chen.pojo;
public class User {
private String name;
public User(String name) {
this.name = name;
}
public void show() {
System.out.println("name=" + name);
}
}
UserT.class
package com.chen.pojo;
public class UserT {
private String name;
public UserT(){
System.out.println("UserT被創建了");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show() {
System.out.println("name=" + name);
}
}
2.创建Spring容器xml文件.
每个xml可以对应一个实体类,然后汇总到一个总的xml中使用.
applicationContext.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">
<import resource="beans.xml"/>
<import resource="beans1.xml"/>
<import resource="beans2.xml"/>
</beans>
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="user" class="com.chen.pojo.User">
<constructor-arg name="name" value="秦寿"/>
</bean>
<bean id="userT" class="com.chen.pojo.UserT" name="userT2 userT3">
<property name="name" value="kuangstudy.com"/>
</bean>
</beans>
beans1.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">
</beans>
beans2.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">
</beans>
3.在test/java文件夹内创建MyTest.class进行测试
import com.chen.pojo.User;
import com.chen.pojo.UserT;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user =(User) context.getBean("user");
user.show();
System.out.println();
UserT userT =(UserT) context.getBean("userT");
userT.show();
UserT userT2 =(UserT) context.getBean("userT2");
userT2.show();
UserT userT3 =(UserT) context.getBean("userT3");
userT3.show();
}
}
|