User
package com.liu.pojo;
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name="+name);
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
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
http://www.springframework.org/schema/beans/spring-beans.xsd">
无参构造默认赋值
<bean id="user" class="com.liu.pojo.User">
<property name="name" value="向阳"/>
</bean>
</beans>
MyTest
import com.liu.pojo.User;
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");
System.out.println(user.toString());
}
}
## pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>myliu-02</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.10</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
如果User中存在有参构造
package com.liu.pojo;
public class User {
private String name;
private User(String name){
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name="+name);
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
applicationcontext.xml
1.还可以用下标赋值
<bean id="user" class="com.liu.pojo.User">
<constructor-arg index="0" value="张三"/>
</bean>
2.类型赋值
<bean id="user" class="com.liu.pojo.User">
<constructor-arg type="java.lang.String" value="张三"/>
</bean>
无参构造默认赋值
<bean id="user" class="com.liu.pojo.User">
<property name="name" value="向阳"/>
</bean>
|