第二节 Spring程序开发步骤

亮子 2021-06-10 15:28:20 17485 0 0 0

1)、 创建普通maven项目

图片alt

2)、添加依赖

<?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>com.shenmazong</groupId>
    <artifactId>server-ssm-01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
    </dependencies>

</project>

3)、创建bean

(1)、创建接口

package com.shenmazong.service;

public interface UserService {
    void whoAmI();
}

(2)、创建实现类

package com.shenmazong.service.impl;

import com.shenmazong.service.UserService;

public class UserServiceImpl implements UserService {
    @Override
    public void whoAmI() {
        System.out.println("i am shenmazong...");
    }
}

4)、创建applicationContext.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="whoAmI" class="com.shenmazong.service.impl.UserServiceImpl"></bean>
</beans>

5)、获取bean

package com.shenmazong.demo;

import com.shenmazong.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class WhoAmIDemo {
    public static void main(String[] args) {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService whoAmI = (UserService) app.getBean("whoAmI");
        whoAmI.whoAmI();
    }
}

6)、运行项目

图片alt