Spring IOC创建对象的两种方式

网友投稿 550 2023-02-06

Spring IOC创建对象的两种方式

Spring IOC创建对象的两种方式

IOC创建对象的方式

一、 使用无参构造创建对象(默认方式)

创建实体类

注意:属性必须要有set方法,来完成注入

public class User {

private String name;

public User() {

System.out.println("执行了User类的无参构造方法~");

}

public User(String name){

this.name = name;

System.out.println("执行了User类的有参构造方法");

}

//使用无参构造方法时,必须要设置set方法,因为注入时 需要通过set方法注入

public void setName(String name) {

this.name = name;

}

@Override

public String toString() {

return "User{" +

"name='" + name + '\'' +

'}';

}

}

配置Bean

xmlns:xsi="http://w3dfCqSVNz.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans

https://springframework.org/schema/beans/spring-beans.xsd">

xmlns:xsi="http://w3dfCqSVNz.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://springframework.org/schema/beans

https://springframework.org/schema/beans/spring-beans.xsd">

测试类

public class MyTest {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

User user = context.getBean("user", User.class);

System.out.println(user);

http:// }

}

​ 结果:

二、使用有参构造创建对象

通过下标注入

通过名字注入 【推荐】

通过类型注入

有参构造,不需要set方法http://注入

通过下标方式注入(通过index来选择,给有参构造的第几个参数注入)

(1)配置Bean

(2)测试结果

通过名字注入

(1)配置Bean

(2)测试结果

通过类型注入(不建议使用!因为当类里面有两个相同类型的属性时,无法给属性注入)

(1)配置Bean

(2)测试结果

总结:在加载配置文件的时候,IOC就已经创建好了对象!

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:微信小程序前端存储安全(微信小程序是否安全)
下一篇:抖音app运营模式(抖音app运营模式分析)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~