Spring的核心基础:感受一下对象工厂

“欢迎来到Spring!”的小项目

(1)写一个HelloSpring的类,采用setter方法注入userName,写一个简单的show方法。

package com.itzhoutao;
public class  HelloSpring{
	private String userName;

	public void setUserName(String userName)
	{
		this.userName = userName;
	}

	public void show(){
		System.out.println(userName + ":欢迎来到Spring!");
	}

}

(2)利用Spring容器,如ApplicationContext,初始化容器,加载xml配置,获取(getBean)实例。写了一个TestHelloSpring类。

package com.itzhoutao;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestHelloSpring {
    public static void main(String[] args) {
        //初始化spring容器,加载applicationContext.xml配置
        ApplicationContext applicationContext = new
                ClassPathXmlApplicationContext("applicationContext.xml");
        //通过容器获取配置中helloSpring的实例
        HelloSpring helloSpring =
                (HelloSpring) applicationContext.getBean("helloSpring");
        helloSpring.show();//调用方法
    }

}

3.applicatiomContext.xml的信息:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 将指定类配置给Spring,让Spring创建HelloSpring对象的实例 -->
    <bean id="helloSpring" class="com.itzhoutao.HelloSpring">
        <!--为userName属性赋值-->
        <property name="userName" value="土豆哥哥"></property>
    </bean>
</beans>

手动管理j的ar包和这个项目的基本结构:

jar包在springlibs目录下,相关程序代码写在了work目录下。

手动编译运行Spring项目的方法:

1. 将Spring所需的所有jar包(含commons-logging的jar包)文件放到C:\Program Files\Java\jre1.8.0_181\lib\ext的目录下,并另外存放一份放到源码所在位置的springlibs目录下。

2. 将所有的.java源码文件放到某个工作文件夹比如work中(注意只要.java的文件,不要包名对应的文件夹),将所需的xml配置文件也拷贝到本文件夹中。

3. 进入work工作文件夹,然后在命令行下运行编译命令:javac -d . *.java -encoding utf8 -classpath ..\springlibs\* 即可成功编译。

4. 运行:在work工作文件夹中,运行命令:java 主类的包名.类名。

  • 9
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值