概念:Spring 是一个轻量级(低耦合)的开源框架,用于管理bean和维护bean与bean之间的关系

 

1. 新建java项目spring_1

2. 新建lib文件夹导入jar包,并add build path

commons-collections-3.2.jar
commons-logging.jar
spring-aop-4.0.6.RELEASE.jar
spring-beans-4.0.6.RELEASE.jar
spring-context-4.0.6.RELEASE.jar
spring-core-4.0.6.RELEASE.jar
spring-expression-4.0.6.RELEASE.jar

 

3. 新建HelloWorld类

 1 package com.yf.hello;
 2 
 3 public class HelloWorld {
 4     
 5     private String name ;
 6 
 7     public String getName() {
 8         return name;
 9     }
10 
11     public void setName(String name) {
12         System.out.println("setName="+name);
13         this.name = name;
14     }
15     
16     public HelloWorld(){
17         System.out.println("constructor1.."+name);
18     }
19     
20 
21     public HelloWorld(String name) {
22         this.name = name;
23         System.out.println("constructor2.."+name);
24     }
25 
26     @Override
27     public String toString() {
28         return "HelloWorld [name=" + name + "]";
29     }
30 }

 

4. 新建spring的配置文件 applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xsi:schemaLocation="http://www.springframework.org/schema/beans
 5         http://www.springframework.org/schema/beans/spring-beans.xsd">
 6 
 7     <bean id="helloWorld" class="com.yf.hello.HelloWorld" >
 8         <property name="name"><value>zhangsan</value></property>
 9         <!-- <constructor-arg type="String" value="李四"></constructor-arg> -->
10     </bean>
11 </beans>

 

5. 新建测试类:

 1 package com.yf.hello;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class Main {
 7 
 8     public static void main(String[] args) {
 9         ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
10         HelloWorld helloWorld = (HelloWorld) ac.getBean("helloWorld");
11         System.out.println(helloWorld);
12     }
13 
14 }

 注: 使用属性注入bean时,需要确保该类有默认的构造方法(通过反射方式)

 

posted @ 2017-08-14 16:07 炒涨英 阅读(2) 评论(0) 推荐(0)
只有注册用户登录后才能阅读该文。 阅读全文
posted @ 2017-07-15 09:55 炒涨英 阅读(3) 评论(0) 推荐(0)
摘要: 1.什么是反射? 反射就是将 java 类各个成分映射成相应的 java 类。 JAVA反射机制是在 运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。 2.反射有什么 阅读全文
posted @ 2017-06-30 09:35 炒涨英 阅读(107) 评论(0) 推荐(0)
摘要: String类 “==”与“equals()”的区别 “==” 是java提供的关系运算符,主要功能是进行数值相等判断的,如果用在了String对象上,表示的是内存地址数值的比较; “equals”是由String提供的一个方法,负责进行字符串内容的比较 在开发时,如果要判断输入的内容是否是某一字符 阅读全文
posted @ 2017-06-29 16:16 炒涨英 阅读(96) 评论(0) 推荐(0)
点击右上角即可分享
微信分享提示