0
点赞
收藏
分享

微信扫一扫

用Spring工厂实例化对象

人间四月天i 2022-11-22 阅读 97


如何导入spring相关包,以及基本的配置及应用spring工厂

spring的作用有多大,它代表的不仅仅是spring框架本身,在前辈的更新下,已经能无脑支持structs , mybatis, hibernate等各种框架了,想要使用各种框架的码宅们只需要引入相关依赖包就能直接使用各种框架了。
本文旨在教会新手们如何引入相关依赖包,以及在引包时应该注意的地方,并且简单地用spring自带的工厂,来做一个小小的应用示范。

主包

spring-core-3.2.4.RELEASE.jar

按需引包

spring-aop-3.2.4.RELEASE.jar

spring-aspects-3.2.4.RELEASE.jar

spring-beans-3.2.4.RELEASE.jar

spring-build-src-3.2.4.RELEASE.jar

spring-context-3.2.4.RELEASE

spring-context-support-3.2.4.RELEASE.jar


部分依赖包

commons-logging-1.0.3.jar


spring3的相关包哪里有下载呢,csdn-下载-搜索里太多了,笔者不多谈。

引包

1.准备好需要用到的jar包

用Spring工厂实例化对象_jar

2.全选,复制,在Myeclipse的新工程下,新建一个lib的文件夹

用Spring工厂实例化对象_xml_02


然后粘贴进去。3.把这个lib下的jar包添加进引用,右键工程-build path-Libraries-add external jars- 选中工程路径下lib文件夹里你刚刚粘贴进去的包-确定

用Spring工厂实例化对象_xml_03

这里笔者只引了一部分!

这里有人可能对lib比较疑惑,新建的lib文件夹不会被自动引入的,必须通过手动引入,就是上面的第三步,工程路径怎么找,右键工程-properties-选中:

用Spring工厂实例化对象_spring_04


看,Location就是工程路径,里面就有我们刚刚新建的lib文件夹。

代码

主类:
package com;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClass {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
BeanFactory bf =new ClassPathXmlApplicationContext("applicationContext.xml");
IMessage msg = (IMessage)bf.getBean("msg");
msg.getMessage();
}
}

Message类:
package com;

public class Message implements IMessage {

public void getMessage(){
System.out.println("info");
}
}

IMessage接口:
package com;

public interface IMessage {

public abstract void getMessage();

}

然后看一下配置文件applicationContext.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">

<bean id="msg" class="com.Message"></bean>

</beans>

配置文件里,上面的写法引用都是固定的,下面只添加了一个id=”msg”的bean,这是为什么主类可以通过bf.getBean(“msg”)获取到实例。
输出结果就是: info
不做附图了。

笔者在引用jar包的时候是先放入一个新建的lib,再把他添加到libraries里面去,如果大家嫌懒,而且工程正好又是一个web工程,那就可以直接把包丢进WEB-INFO的lib里面去,就不需要上述的添加步骤了。

用Spring工厂实例化对象_spring_05


复制粘贴进去以后,使用需要的包的时候,只要ctrl+shift+o就行。


举报

相关推荐

0 条评论