1 public class User { 2 private String name; 3 4 public User() { 5 System.out.println("User的无参构造"); 6睿共享 } 7 8 pu睿共享 blic String getName() { 9 return name; 10 } 11 12 public void setName(String name) { 13 this.name = name; 14 } 15 16 }
1 "1.0" encoding="UTF-8"?> 2"http://www.springframework.org/schema/beans" 3 xmlns_xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi_schemaLocation="http://www.springframework.org/schem 睿共享 a/beans 5 https://www.springframework.org/schema/beans/spring-beans.xsd"> 6"user" class="com.rzk.pojo.User"> 7 9 10 11"name" value="小明"/>默认使用无参设置值 8
1 public class Mytext { 2 public static void main(String[] args) { 3 ApplicationContext context = new ClassPathXmlApplicatio睿共享 nContext("applicationContext.xml"); 4 User user = (User) context.getBean("user"); 5 6 application一注册就实例化 7 } 8 }
当我们创建ApplicationContext对象的时候 同时会将 配置文件中配置的bean对象一起创建
(饿汉模式 )这时候无参构造也被加载
上面是使用无参设置值
下面是有参设置
1 public class User { 2 private String name; 3 4 public User(String name) { 5 this.name = name; 6 System.out.println("User的有参构造"); 7 } 8 9 public String getName() { 10 return name; 11 } 12 13 public void setName(String name) { 14 this.name = name; 15 } 16 17 }
直接通过参数名设置值
1 "1.0" encoding="UTF-8"?> 2"http://www.springframework.org/schema/beans" 3 xmlns_xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi_schemaLocation="http://www.springframework.org/schema/beans 5 https://www.springframework.org/schema/beans/spring-beans.xsd"> 6 "user" class="com.rzk.pojo.User"> 7 8 10"name" value="小明" />使用有参注入值 9
通过下标赋值
1 public class User { 2 private String name; 3 private int age; 4 5 public User(String name, int age) { 6 this.name = name; 7 this.age = age; 8 System.out.println("User的有参构造"); 9 } 10 11 public String getName() { 12 return name; 13 } 14 15 public void setName(String name) { 16 this.name = name; 17 } 18 19 public int getAge() { 20 return age; 21 } 22 23 public void setAge(int age) { 24 this.age = age; 25 } 26 }
1 "1.0" encoding="UTF-8"?> 2"http://www.springframework.org/schema/beans" 3 xmlns_xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi_schemaLocation="http://www.springframework.org/schema/beans 5 https://www.springframework.org/schema/beans/spring-beans.xsd"> 6 "user" class="com.rzk.pojo.User"> 7 10"0" valu 睿共享 e="小明" /> 8"1" value="12"/> 9