1.项目创建
maven 中的 quickstart
可以覆写原地址,选择自己的文件夹
home path 可以选择本地maven文件夹
setting file path 选择 maven 文件夹下的 conf里的setting文件
选择自己以前用过的本地repo即可
2.添加maven依赖
创建完成后,在出现的xml页面里的依赖中添加以下代码以引入spring框架
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
外部库里没有显示spring被引入 可以在依赖里添加本地地址(我失败了,先用另一种)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.4.RELEASE</version>
<scope>system</scope>
<systemPath>D:\JAVA\maven\maven-repo\org\springframework\spring-context\5.2.4.RELEASE\spring-context-5.2.4.RELEASE.jar</systemPath>
</dependency>
或者手动引入 点 + 然后点 java 选择路径
可以看到,成功引入了
3.配置beans
main下新建 resource 文件夹,创建文件命名 beans.xml,
粘贴以下代码,component-scan 表示自动扫描 ,base-package="你自己的路径" 。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="org.example"></context:component-scan>
<aop:aspectj-autoproxy/>
</beans>
创建一个装main的java类 这里命名app 在main函数里里写出 ClassPathXmlApplicationContext
(很可能是手动 import)
并且创建一个用于测试beans的类,这里叫TestBean,加入 @Component
package org.example;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class app {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext ("beans.xml");
}
}
package org.example;
import org.springframework.stereotype.Component;
@Component
public class TestBean {
// 无参构造一个TestBean
public TestBean(){
System.out.println("测试:我是 " + getClass());
}
}
4.测试与问题解决
好了 在main里运行一下,结果
又报错,再引入
继续导入
就一直导导导,导到停止报错,啊不,是导出来了新种类错误
定睛一看,是刚刚导入的 jar包 还没有在 pom.xml里 写依赖,这就写上
<!-- springAop依赖包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.4.RELEASE</version>
</dependency>
<!-- springAop依赖Aspect的语法标准包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.7.RELEASE</version>
</dependency>
再次运行,成功 :