基于Maven的Spring开发环境搭建也很简单,和基于Maven的Mybatis开发环境搭建类似.下面我们来进行介绍:
Spring核心框架在Maven中的项目坐标如下:
-
-
- <dependency>
- <groupId>org.springframeworkgroupId>
- <artifactId>spring-contextartifactId>
- <version>5.2.2.RELEASEversion>
- dependency>
注:
此处我们只需要导入上述Spring的核心jar包即可,无需导入其他多余Spring有关jar包.因为Maven会为我们自动导入Spring核心jar包所需的其他必要jar包.
junt jar包在Maven中的项目坐标如下:
-
-
- <dependency>
- <groupId>junitgroupId>
- <artifactId>junitartifactId>
- <version>4.12version>
- <scope>testscope>
- dependency>
我们在创建时一定要生成类中的get(),set()方法,以及写出它的无参构造和有参构造方法
- package com.ffyc.springdemo.model;
-
- public class Admin {
-
- private int id;
- private String name;
-
- public Admin() {
- System.out.println("Admin无参构造");
- }
-
- public Admin(int id, String name) {
- this.id = id;
- this.name = name;
- }
-
- public int getId() {
- return id;
- }
-
- public void setId(int id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Override
- public String toString() {
- return "Admin{" +
- "id=" + id +
- ", name='" + name + '\'' +
- '}';
- }
- }
-
该文件用于描述Bean的定义信息,Spring根据这些信息创建和管理对象
- "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="admin" class="com.ffyc.springdemo.model.Admin">
-
-
- <property name="id" value="1">property>
- <property name="name" value="飞飞">property>
-
- bean>
- beans>
-
注:
xml文件中用到的属性暂时简单介绍如下,之后会在SpringBean文章中详细介绍
class: 指定Bean的实现类,它必须使用类的全限定名
id: Bean的唯一标识符,Spring容器对Bean的配置,管理都通过该属性进行.
- package com.ffyc.springdemo.test;
-
- import com.ffyc.springdemo.model.Admin;
- import org.junit.jupiter.api.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
-
- public class Test1 {
-
- @Test
- public void test() {
-
- ApplicationContext app = new ClassPathXmlApplicationContext("spring.xml");
- Admin admin = app.getBean("admin",Admin.class);
- System.out.println(admin);
- }
- }
-