需要导入的jar包参考:
<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.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>Spring_04artifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<maven.compiler.source>11maven.compiler.source>
<maven.compiler.target>11maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>3.8.1version>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.29version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.6version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.2.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.2.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.11version>
dependency>
dependencies>
project>
创建jdbc连接数据库相关配置的bean(driver,url,username,password):
为了解耦,将配置参数driver、url、username、password提取到配置文件中进行具体的赋值,其具体操作为:
所对应的具体值放在类的外部文件中:
书写格式样例为:
中心思路:就是将两个方法配置为Bean,放在Ioc容器中提供使用:
接下来仔细说说所导入的两个包"com.Alvis.domin":
两个点:
需要注意的是该类的继承接口Serializable不能漏写
然后就是"com.Alvis.dao"包:
最后的一个配置类就是SpringConfig配置类:
在test文件中编写java程序实现需求:
package test;
import com.Alvis.config.SpringConfig;
import com.Alvis.domain.Person;
import com.Alvis.service.PersonService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.List;
public class App_01 {
public static void main(String[] args) {
ApplicationContext apx = new AnnotationConfigApplicationContext(SpringConfig.class);
PersonService personService = apx.getBean(PersonService.class);
Person personSelect = personService.selectById(2);
System.out.println(personSelect);
}
}
=======================================
8月 20, 2022 9:44:29 下午 com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl info
信息: {dataSource-1} inited
Person{id=2, name='李四', age=95, address='上海'}
进程已结束,退出代码0