1,Main 文件
- package com.pb;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- /**
- *
- * 项目名称: PB_SpringDemo
- * 类名称: HellpSpring
- * 类描述: 第一个 Spring 项目
- * 创建人: Administrator
- * 创建时间: 2019 年 7 月 6 日 上午 7:23:43
- * 修改人: Administrator
- * 修改时间: 2019 年 7 月 6 日 上午 7:23:43
- * 修改备注:
- * @version
- *
- */
- public class HelloSpring {
- // 需要注入的属性, 这个名字跟 Bean 里的没有任何关系
- private String input_str=null;
- /*
- * 注意点 1: 依赖注入的是靠 get 和 set 方法的名字来确认的, 比如本例子中是 getMyStr 和 setMyStr, 那么 Bean 里的属性名字就必须配置为 myStr, 否则出错
- * 注意点 2:Bean 的属性名字必须是首字母小写, 如本例中是 myStr, 不能写成 MyStr, 否则报 [Invalid property 'MyStr' of bean class [com.pb.HelloSpring]: No property 'MyStr' found]
- * 注意点 3:get 和 set 方法必须对应起来, 不能是这样 getMYStr 和 setMyStr, 大小写不一致也会出错
- */
- public String getMyStr() {
- return this.input_str;
- }
- public void setMyStr(String strParam) {
- this.input_str=strParam;
- }
- public void Print()
- {
- System.out.println("Hello,"+this.getMyStr());
- }
- public static void main(String[] args) {
- // 创建 Spring 上下文
- ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
- // 获取 bean 的实例
- HelloSpring helloSpring=(HelloSpring)context.getBean("myFirstSpringDemo");
- helloSpring.Print();
- }
- }
- 2,applicationContext.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
- "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
- <beans>
- <bean id="myFirstSpringDemo" class="com.pb.HelloSpring">
- <property name="myStr">
- <value > 我是 Spring</value>
- </property>
- </bean>
- </beans>
运行效果
3, 注意点
* 注意点 1: 依赖注入的是靠 get 和 set 方法的名字来确认的, 比如本例子中是 getMyStr 和 setMyStr, 那么 Bean 里的属性名字就必须配置为 myStr, 否则出错
* 注意点 2:Bean 的属性名字必须是首字母小写, 如本例中是 myStr, 不能写成 MyStr, 否则报 [Invalid property 'MyStr' of bean class [com.pb.HelloSpring]: No property 'MyStr' found]
* 注意点 3:get 和 set 方法必须对应起来, 不能是这样 getMYStr 和 setMyStr, 大小写不一致也会出错
来源: http://www.bubuko.com/infodetail-3114818.html