赞
踩
一、依赖注入的类:两种方法 构造方法注入、setter注入
FIRST
1.构造方法注入:首先写出基本要求
2.在资源文件中填入bean信息
注 :<constructor-arg> 为属性 为构造器内属性赋值,可以不按照顺序赋值。
3.Test测试
- import com.itheima.User1;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- public class TestUser1 {
- public static void main(String[] args) throws Exception {
- //加载ApplicationContext.xml配置(资源文件信息获取)
- ApplicationContext applicationContext =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- //获取配置中User1实例 getBean()获取Spring容器中的bean信息
- User1 user1 = applicationContext.getBean("user1",User1.class);
- System.out.println(user1);
- }
- }
4.result
SECOND
1.setter注入:
- package com.itheima;
-
- public class User2 {
- private int id;
- private String name;
- private int password;
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getPassword() {
- return password;
- }
-
- public void setPassword(int password) {
- this.password = password;
- }
-
- public String toString(){
- return "id="+id+",name="+name+",password="+password;
- }
- }

2.bean
- <bean id="user2" class="com.itheima.User2">
- <property name="id" value="2"></property>
- <property name="name" value="bro"></property>
- <property name="password" value="467"></property>
- </bean>
- //在bean中设置属性时,必须有set get方法,否则无法在property中设置。
3.Test
- public class TestUser2 {
- public static void main(String[] args) throws Exception {
- ApplicationContext applicationContext =
- new ClassPathXmlApplicationContext("applicationContext.xml");
- User2 user2 = applicationContext.getBean("user2",User2.class);
- System.out.println(user2);
- }
- }
4.Result
2.getBean方法的选择
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。