Spring创建对象

使用Spring创建对象

1、导入jar包(这里用的是maven)

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.9.RELEASE</version>
    </dependency>

2、编写代码

1、编写一个Hello实体类

public class Hello {
   private String name;

   public String getName() {
       return name;
  }
   public void setName(String name) {
       this.name = name;
  }

   public void show(){
       System.out.println("Hello,"+ name );
  }
}

2、编写我们的spring文件 , 这里我们命名为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就是java对象 , 由Spring创建和管理-->
   <bean id="hello" class="com.kuang.pojo.Hello">
       <property name="name" value="Spring"/>
   </bean>

</beans>

3、我们可以去进行测试了 .

@Test
public void test(){
   //解析beans.xml文件 , 生成管理相应的Bean对象
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   //getBean : 参数即为spring配置文件中bean的id .
   Hello hello = (Hello) context.getBean("hello");
   hello.show();
}

思考:

  • Hello对象是谁创建的?--------------------hello对象由Spring创建
  • Hello对象的属性是怎么设置的?--------------------hello对象的属性是由Spring容器设置的,这个过程就叫控制反转
  • 谁来控制对象的创建-----------传统的应用程序由程序本身控制创建,使用Spring后,对象是由Spring来创建的
  • 反转---------程序本身不创建对象,为变成被动的接受对象

依赖注入 : 就是利用set方法来进行注入的.

IOC是一种编程思想,由主动的编程变成被动的接收

 

原文地址:https://www.cnblogs.com/IanIan/p/14320854.html