Spring-HelloSpring

Spring-HelloSpring,第1张

Spring-HelloSpring 3.1、Spring-01 1.编写实体类:
@Data
public class Hello {
    private String str;
}
2.编写Sping配置文件

官网:



​
      
        
    
​
    
        
    
​
    
​

beans.xml:



        
    
        
    

3.测试

public class MyTest {
    public static void main(String[] args) {
        //获取Spring的上下文对象
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        //对象都在bean中管理,直接从bean中取出即可
        Hello hello = (Hello) context.getBean("hello");
        System.out.println(hello.toString());
    }
}

总结:

  1. Hello对象是由Spring创建的,Hello对象的属性是由SPringle容器设置的

  2. 控制反转:

    1. 控制:控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring创建的

    2. 反转:程序本身不创建对象,而变成被动的接收对象

  3. 依赖注入:利用Set方法注入

3.2、service层调dao层 1.xml文件的配置
public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
}


​
​
    
    
        
        
        
    
2.测试
public class MyTest {
    public static void main(String[] args) {
        //获取ApplicationContext;拿到Spring容器
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
        userServiceImpl.getUser();
​
    }
}

现在 , 不用再程序中去改动了 , 要实现不同的 *** 作 , 只需要在xml配置文件中进行修改 .

所谓的IoC: 对象由Spring 来创建 , 管理 , 装配 !

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5563721.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-14
下一篇2022-12-14

发表评论

登录后才能评论

评论列表(0条)

    保存