第一个Spring Demo

目录

1、Main文件

2、applicationContext.xml

3、注意点


 

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,大小写不一致也会出错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值