Spring | 我人生中第一个使用IOC的程序【常规基本用法】

本文通过一个登录注册邮箱程序实例,介绍了如何基于Spring的IOC进行控制反转操作。借助廖雪峰的文章理解IOC原理,实现了MailService和UserService模块,简化了数据库交互过程,避免了大量原生JDBC的繁琐代码。
摘要由CSDN通过智能技术生成

这是一个繁星满天的一个普通的夜,

是的,我在看Spring IOC,

IOC Inversion of Control 控制反转 具体参见 廖雪峰 | IOC原理 

我这里直接上代码了。

俗话说,

站在巨人的肩膀上看世界,

世界或许更简单,

不错,

我今天就站在廖雪峰大爷的肩膀上,

展望我的Spring处女程序,

这感觉不是一般的特别!

言归正传。

 

场景:

我这里要写的是一个登录注册建议的邮箱程序(借鉴廖雪峰大爷),

其中,涉及两个模块,

一个是MailService ,用于提示用户的登录、注册状态。

另一个是UserService,顾名思义,用户用来登录、注册、或者操纵数据库。

我这篇文章,是站在廖雪峰大爷的肩膀上,写了一些自己的东西,有了一点自己的思考而已,看这篇之前,最好还是先看看这个连接文章 廖雪峰 | IOC原理 。

关于Spring IOC 的故事,就在MailService与UserService之间展开了,

至于后来的dataSource这个小三,则是复现了MailService与UserService之间的操作而已(同时被注入)。

目录结构【取自廖雪峰大爷处】:

规范步骤:

1. 在pom.xml中引入相关依赖,并配置常规的编码等方面的基本信息

  • Spring-context
  • c3p0
  • mysql-connector-java

2. 写一个MailService (提示用户何实何地对邮箱做了什么,比如夜里两点半在马达加斯加登录了邮箱这类提示信息)

    再写一个UserService (实现用户做了什么,比如登录注册邮箱)

    还需要写一个User类,毕竟需要使用到这个东西。

3. 站在2中已完成的MailService与UserService的基础上,完成application.xml

4.最后写我们的Main方法,执行我们的程序。

具体的代码:

1.pom.xml

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.itranswarp.learnjava</groupId>
  <artifactId>spring-ioc-appcontext</artifactId>
  <version>0.0.1-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <java.version>11</java.version>

        <spring.version>5.2.3.RELEASE</spring.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        
        <dependency>  
		    <groupId>c3p0</groupId>
		    <artifactId>c3p0</artifactId>
		    <version>0.9.1.2</version>     
		</dependency>   
		<dependency>
		    <groupId>mysql</groupId>
		    <artifactId>mysql-connector-java</artifactId>
		    <version>8.0.20</version>   
		</dependency> 
    </dependencies>
</project>
  

2. MailService.java

package com.itranswarp.learnjava.service;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/*
 * 邮件登录提醒
 * 邮箱注册提醒
 */
public class MailService {
	private ZoneId zoneId = ZoneId.systemDefault();

    public void setZoneId(ZoneId zoneId) {
        this.zoneId = zoneId; //获取当前时区
    }

    public String getTime() {
        return ZonedDateTime.now(this.zoneId).format(DateTimeFormatter.ISO_ZONED_DATE_TIME);//获取当前时区下的具体时间
    }

    public void sendLoginMail(User user) {
        System.err.println(String.format("Hi, %s! You are logged in at %s", user.getName(), getTime()));//用户登陆的时间提醒
    } 

    public void sendRegistrationMail(User user) {
        System.err.println(String.format("Welcome, %s!", user.getName())); //用户注册的时间提醒

    }

}

UserService.java

package com.itranswarp.learnjava.service;


import java.sql.Connection;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;



public class UserService {
	private MailService mailService;
	private DataSource dataSource;
	 
	 
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	public void setMailService(MailService mailService) {
        this.mailService = mailService;
    }
    
    

    private List<User> users = new ArrayList<>(List.of( // users:
            new User(1, "bob@example.com", "password", "Bob"), // bob
            new User(2, "alice@example.com", "password", "Alice"), // alice
            new User(3, "tom@example.com", "password", "Tom")
            )
    		); // tom

    public User login(String email, String password) {
        for (User user : users) {
            if (user.getEmail().equalsIgnoreCase(email) && user.getPassword().equals(password)) {
                mailService.sendLoginMail(user);
                return user;
            }
        }
        throw new RuntimeException("login failed.");
    }
    public void loginindb(String email, String password) throws SQLException, ClassNotFoundException {
       Connection connection = dataSource.getConnection();
       String sql = "INSERT INTO email VALUES(null,?,?,null)";
       PreparedStatement preparedStatement = connection.prepareStatement(sql);
       preparedStatement.setString(1, email);
       preparedStatement.setString(2, password);
       int executeUpdate = preparedStatement.executeUpdate();
       System.out.println(executeUpdate);
    }
    
    public List<User> getAllUsers(){
    	
		return users;
    	
    } 

    public User getUser(long id) {
        return this.users.stream().filter(user -> user.getId() == id).findFirst().orElseThrow();
    }

    public User register(String email, String password, String name) {
        users.forEach((user) -> {
            if (user.getEmail().equalsIgnoreCase(email)) {
                throw new RuntimeException("email exist.");
            }
        });
        User user = new User(users.stream().mapToLong(u -> u.getId()).max().getAsLong() + 1, email, password, name);
        users.add(user);
        mailService.sendRegistrationMail(user);
        return user;
    }

}

User.java

package com.itranswarp.learnjava.service;

public class User {
	public long id;
	public String email;
	public String password;
	public String name;
	public User(long id, String email, String password, String name) {
		super();
		this.id = id;
		this.email = email;
		this.password = password;
		this.name = name;
	}
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String toString() {
		return "User [id=" + id + ", email=" + email + ", password=" + password + ", name=" + name + "]";
	}
	

}

3.application.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
    					http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    

    <bean id="userService" class="com.itranswarp.learnjava.service.UserService">
        <property name="mailService" ref="mailService" />
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean id="mailService" class="com.itranswarp.learnjava.service.MailService" />
    
   	<!--创建数据源bean   -->
   	

	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jdbc_test"></property>
		<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
		<property name="user" value="root"></property>
		<property name="password" value="88888888"></property>
	</bean>

</beans>

4.Main.java

package com.itranswarp.learnjava;



import java.sql.SQLException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.itranswarp.learnjava.service.MailService;
import com.itranswarp.learnjava.service.UserService;


public class Main {
	public static void main(String[] args) throws SQLException, ClassNotFoundException {

		 
		//我们需要创建一个Spring的IoC容器实例,然后加载配置文件,让Spring容器为我们创建并装配好配置文件中指定的所有Bean
		  ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");   
		  UserService userService = context.getBean(UserService.class); 
		  userService.loginindb("0000000", "sbsbsb");  
	}
}

/*
 * 1.在pom.xml中引入spring-context的依赖 2.先编写一个MailService,用于在用户登录和注册成功后发送邮件通知:
 * 3.再编写一个UserService,实现用户注册和登录:
 * 4.注意到UserService通过setMailService()注入了一个MailService。
 * 然后,我们需要编写一个特定的application.xml配置文件,告诉Spring的IoC容器应该如何创建并组装Bean:
 * 5.最后一步,我们需要创建一个Spring的IoC容器实例,然后加载配置文件,让Spring容器为我们创建并装配好配置文件中指定的所有Bean,
 * 这只需要一行代码: ApplicationContext context = new
 * ClassPathXmlApplicationContext("application.xml"); 具体的main完整程序:
 */

【END】

我算是体会到,

Spring来连接数据库的时候,

真的,真的,真的,

不需要像原生JDBC那样烦人,

写一大堆代码,

相反,

我们只需要,

从建立来连接开始,

即可!

(在UserService内)

       Connection connection = dataSource.getConnection();
       String sql = "INSERT INTO email VALUES(null,?,?,null)";
       PreparedStatement preparedStatement = connection.prepareStatement(sql);
       preparedStatement.setString(1, email);
       preparedStatement.setString(2, password);
       int executeUpdate = preparedStatement.executeUpdate();

---------------------------------------------------------------------------------

求真务实

熟能生巧

抓紧时间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北溟南风起

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值