Sping 安装配置
1、Eclipse下安装配置(默认配置JDK环境)
-
jar包下载
spring下载路径: spring安装路径(https://repo.spring.io/release/org/springframework/spring/)
-
导入基本的jar包
创建一个web 项目,在下载的spring文件中的lib目录下复制jar包导入eclipse,spring-aop-4.1.6.RELEASE.jar,x-beans-x,x-context-x,x-core-x,x-context-support-x(x代表相同的前后缀)
(Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
出现上述报错:下载apache commons logging 包
apache.commons.logging 下载,导入即可) -
编写代码
- 1、bean配置文件
<bean id="person(唯一标识符)" class="bean类的全类名(如:java.lang.String)">
<property name="name" value="pp"></property>
<property name="age" value="44"></property>
</bean>
创建的.xml文件记得在/路径下 具体文件头参照:..\spring-framework-4.1.6.RELEASE\docs\spring-framework-reference\html\beans.html (下载的spring-framework-4.1.6.RELEASE中) - 2、获取IoC容器中的Bean实例
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Object person = context.getBean("person");
Person person2 = context.getBean("person",Person.class);
System.out.println(person); //通过beans.xml 中配置的bean的id
System.out.println(person2); //指定类
2、IDEA-Maven配置(默认已安装IDEA)
- 创建Maven项目
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210413173408191.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzM2MDkwMQ==,size_16,color_FFFFFF,t_70 - 导入依赖
在pom.xml中
<properties>
<spring.version>4.1.6.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
- 编写代码
编写beans.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">
<bean id="user" class="com.huang.dao.User">
<property name="name" value="pp"/>
</bean>
</beans>
ApplicationContext context =new ClassPathXmlApplicationContext("beans.xml");
Object user = context.getBean("user");
System.out.println(user);
本人新手,文章有误还请大佬斧正,万分感谢!