Spring IoC容器xml檔案建立物件的三種方式
阿新 • • 發佈:2021-05-09
建立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();
}
}
執行結果