创建pojo类
public class User {
public User(String name) {
this.name = name;
}
private String name;
public void show(){
System.out.println("name=" + name);
}
}
创建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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="User" class="com.example.maventest.hellpspring.pojo.User">
<!-- 第一种 下标赋值 (构造器注入) 三种xml有参构造的注入方式-->
<constructor-arg index="0" value="威威">
</constructor-arg>
<!-- 第二种 类型赋值 不建议使用 参数多了不好分清 -->
<!-- <constructor-arg type="java.lang.String" value="威威的第二种赋值方式 ">-->
<!-- </constructor-arg>-->
<!-- 第三种 直接通过参数名称来进行设置 -->
<!-- <constructor-arg name="name" value="威威威">-->
<!-- </constructor-arg>-->
</bean>
</beans>
创建主类
public class MyTestIoCCreate {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User)context.getBean("User");
user.show();
}
}
运行结果