zoukankan      html  css  js  c++  java
  • Spring入门(二)——DI



    1. DI

    Dependency Injection,依赖注入。当对象里有属性或对象的时候,就需要为这些属性或对象赋值


    2. 流程

    这里介绍两种方式

    • set方法
    • 注解方式

    2.1 set方法

    Bean准备

    package bean;
    
    import bean.Question;
    
    public class User {
    	
    	private String name;
    	private String email;
    	private String password;
        private Question question;
    	
    	/**
        * 省略了getters/setters
        * @author Howl
        */
        
        //set方法
        public void setQuestion(Question question) {
           this.question = question;
        }
    	
    	//构造函数
    	public User(String name, String email, String password) {
    		super();
    		this.name = name;
    		this.email = email;
    		this.password = password;
    	}
    }
    
    package bean;
    
    import java.sql.Timestamp;
    import java.util.Date;
    
    public class Question {
    	
    	private int id;
    	private Timestamp time;
    	private String content;
    	
    	/**
        * 省略了getters/setters
        * @author Howl
        */
    	
        //构造函数
    	public Question(int id, Timestamp time, String content) {
    		super();
    		this.id = id;
    		this.time = time;
    		this.content = content;
    	}
    }
    

    applictionContext.xml配置

    <!--创建User对象-->
    <bean id="User" class="User">
        <!-- 依赖注入,setting自动注入 -->
    	<property name="Question" ref="Question"/>
    </bean>
    
     <!--创建Question对象-->
    <bean id="Question" class="Question"></bean>
    

    获取对象

    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    
    //直接获取
    User user = ac.getBean("User");
    


    2.2 注解方式

    注解准备

    package bean;
    
    import bean.Question;
    
    @Component
    public class User {
    	
    	private String name;
    	private String email;
    	private String password;
        private Question question;
    	
    	/**
        * 省略了getters/setters
        * @author Howl
        */
        
        //set方法
        @Autowired
        public void setQuestion(Question question) {
           this.question = question;
        }
    	
    	//构造函数
    	public User(String name, String email, String password) {
    		super();
    		this.name = name;
    		this.email = email;
    		this.password = password;
    	}
    }
    

    获取对象

    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    
    //直接获取
    User user = ac.getBean("User");
    


  • 相关阅读:
    高效App运营必须get的七个推送技巧
    如何预测您的用户即将流失?
    HMS Core赋能移动金融,为行业注入增长新动力
    做好自定义预测,探寻产品增长动能
    Unity平台 | 快速集成华为AGC云数据库服务
    HMS Core Insights第一期直播回顾 – 深入浅出,创新技术与开发者共同推进行业发展!
    多种细分方式浏览销售数据,IAP助您有效洞察市场收益效果
    Unity | 快速集成华为AGC云存储服务
    awk命令
    反转字符串
  • 原文地址:https://www.cnblogs.com/Howlet/p/11980172.html
Copyright © 2011-2022 走看看