1、导入Jar包,目前导入五个基本jar包:
commons-logging-1.2.jar
spring-beans-4.3.10.RELEASE.jar
spring-context-4.3.10.RELEASE.jar
spring-core-4.3.10.RELEASE.jar
spring-expression-4.3.10.RELEASE.jar
2、在src文件夹下新建config文件夹,在config文件夹中新建spring核心配置文件“×××.xml(习惯上命名为:application.xml)”
“application.xml”文件模板:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#overview-distribution-zip
<?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">
<bean id="..." class=“…”>//id值自定义,class值为Java类的包名+类名
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
实例1:
<?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">
<bean id="user" class="model.User"></bean>//spring容器默认为在服务器启动时创建单例User对象,可以添加lazy-init="true”在调用getBean方法的时候创建User对象,添加scope="prototype”创建多例对象
</beans>
3、新建一个Test类,在main方法中
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml”);//参数为spring核心配置文件的文件名“application.xml”
Object u = context.getBean("user”);//参数为“application.xml”配置文件中的id值“user”,获得一个Object对象
User u1 = context.getBean("user", User.class);//第一个参数为“application.xml”配置文件中的id值“user”,第二个参数为Java类的class对象User.class,获得一个User对象
网友评论