当前位置:   article > 正文

Spring初学

Spring初学

一、依赖注入的类:两种方法 构造方法注入、setter注入

FIRST 

1.构造方法注入:首先写出基本要求

2.在资源文件中填入bean信息

 :<constructor-arg> 为属性 为构造器内属性赋值,可以不按照顺序赋值。

3.Test测试

  1. import com.itheima.User1;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class TestUser1 {
  5. public static void main(String[] args) throws Exception {
  6. //加载ApplicationContext.xml配置(资源文件信息获取)
  7. ApplicationContext applicationContext =
  8. new ClassPathXmlApplicationContext("applicationContext.xml");
  9. //获取配置中User1实例 getBean()获取Spring容器中的bean信息
  10. User1 user1 = applicationContext.getBean("user1",User1.class);
  11. System.out.println(user1);
  12. }
  13. }

4.result

 

 

 

SECOND

1.setter注入:

  1. package com.itheima;
  2. public class User2 {
  3. private int id;
  4. private String name;
  5. private int password;
  6. public int getId() {
  7. return id;
  8. }
  9. public void setId(int id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public int getPassword() {
  19. return password;
  20. }
  21. public void setPassword(int password) {
  22. this.password = password;
  23. }
  24. public String toString(){
  25. return "id="+id+",name="+name+",password="+password;
  26. }
  27. }

2.bean

 

 

  1. <bean id="user2" class="com.itheima.User2">
  2. <property name="id" value="2"></property>
  3. <property name="name" value="bro"></property>
  4. <property name="password" value="467"></property>
  5. </bean>
  6. //在bean中设置属性时,必须有set get方法,否则无法在property中设置。

3.Test

  1. public class TestUser2 {
  2. public static void main(String[] args) throws Exception {
  3. ApplicationContext applicationContext =
  4. new ClassPathXmlApplicationContext("applicationContext.xml");
  5. User2 user2 = applicationContext.getBean("user2",User2.class);
  6. System.out.println(user2);
  7. }
  8. }

4.Result

 

总结:

1.//加载ApplicationContext.xml配置(资源文件信息获取)时需要将资源文件名称填写完整:applicationtect.xml.

2.getBean方法的选择

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号