JAVA Spring之Maven
由于Spring框架会产生很多依赖,所以需要用maven来进行管理。
特别注意不要在外部乱下maven,而是直接用eclipse中的插件比较好。如果真的在创建maven时出现了Could not resolve archetype” 问题也不要紧,可以进入windows->preferences->maven->archetpes->Add Remote Catalog而后在catalog Dile中输入:http://repo1.maven.org/maven2/archetype-catalog.xml 。 如果这样不能解决问题,可以将所有maven和eclpise删除,然后重装eclipse。
step1:创建maven项目
在file->new->other中选择maven project,然后默认next当出现要我们选择一个Archetype时,如果之前添加了remote catalog了,可以选择all catalog然后在fliter里输入quickstart,而后在列表中找到maven-archetype-quickstart。
之后下一步输入各种id而后finish即可。
step2:配置依赖pom.xml
先将spring的库像上一篇一样加入进来,然后在pom.xml中增加如下代码,根据每个人的版本不同version可以改变。(当热就算你没有他也会给你开始下载)
增加如下代码:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
而后右键项目名,选择run as->maven clean,console窗口中出现build success就表示创建maven 成功。
step3:主代码
可以在主目录结构下发现一个src/main/java里面有一个”你之前命名的groupid”.”你之前命名的artifactId”的package,他下属一个名为app.java的文件,可以把他改名成HelloWorld.java,而后输入如下代码:
public class HelloWorld2
{
private String name;
public void setName(String name) {
this.name = name;
}
public void sayHello() {
System.out.println("welcome " + name + "to spring world");
}
}
step4:配置bean
而后右键选择项目名->new->other->spring bean configuration file在src/main下创建一个resources文件夹,创建一个applicationContext.xml文件,其中代码增加如下:
<bean id = "helloworld" class = "com.start.hello2.HelloWorld2">
<property name="name" value="sjf0115"></property>
</bean>
step5:测试代码
在com.text.java下创建helloworldtest.java写入如下代码:
package com.start.hello2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Unit test for simple App.
*/
public class HelloWorldTest
{
private static ApplicationContext context;
private static HelloWorld2 helloWorld;
public static void main(String[] args) {
context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 2. 从IOC容器中获取Bean实例
helloWorld = (HelloWorld2)context.getBean("helloworld");
// 3.调用sayHello方法
helloWorld.sayHello();
}
}
注意这里的坑点是不能项目间重复命名。我这里智能用helloworld2,用helloworld就报错了。