新建Maven项目
这里用了maven,得有点maven基础,会导入依赖就行,选择maven项目,直接下一步。
随便取个帅气的项目名,完成。
导入依赖
编辑pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>hello</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- ioc需要的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
</dependencies>
</project>
编写代码
首先,标准的maven项目结构:
org.example.bean.Hello
package org.example.bean;
/**
* @author MaoLongLong
*/
public class Hello {
public Hello() {
System.out.println("对象被创建");
}
public void sayHello() {
System.out.println("Hello World!");
}
}
在main/resources
下新建一个配置文件applicationContext.xml
把Hello注入到spring容器中
<?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 class="org.example.bean.Hello" id="hello"/>
</beans>
如果看不惯顶上的提示,可以配置一下项目结构,然后提示就消失了。
最后在Main中调用
package org.example;
import org.example.bean.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.Objects;
/**
* @author MaoLongLong
*/
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
Hello hello1 = (Hello) ctx.getBean("hello");
hello1.sayHello();
Hello hello2 = ctx.getBean("hello", Hello.class);
hello2.sayHello();
System.out.println(Objects.equals(hello1, hello2));
}
}
输出结果:
对象被创建
Hello World!
Hello World!
true