springIOC学习笔记
目的
让spring统一管理对象的创建
引用
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
xml方式
配置
resources/bean.xml
<!--默认单例-->
<bean id="user" class="com.alvin.pojo.User" scope="singleton"/>
<!--初始化-->
<bean id="user2" class="com.alvin.pojo.User" init-method="init" destroy-method="destroy"/>
<!--静态工厂方式创建实例-->
<bean id="user3" class="com.alvin.utils.BeanFactory" factory-method="createUser"/>
<!--实例工厂模式创建对象-->
<bean id="objectFactory" class="com.alvin.utils.ObjectFactory"/>
<bean id="user4" class="com.alvin.pojo.User" factory-bean="objectFactory" factory-method="createUser"/>
<!--依赖注入!!!-->
<bean id="date" class="java.util.Date"/>
<!--构造方法注入-->
<bean id="user5" class="com.alvin.pojo.User">
<constructor-arg name="id" value="1"/>
<constructor-arg name="name" value="alvin"/>
<constructor-arg name="birthDay" ref="date"/>
</bean>
<!--set注入-->
<bean id="user6" class="com.alvin.pojo.User">
<property name="id" value="2"/>
<property name="name" value="alvin"/>
<property name="birthDay" ref="date"/>
</bean>
<!--p注入,本质还是set-->
<bean id="user7" class="com.alvin.pojo.User" p:id="3" p:name="alvin" p:birthDay-ref="date"/>
<!--集合注入-->
<bean id="user8" class="com.alvin.pojo.User">
<property name="objectArrays">
<array>
<value>123</value>
<bean class="java.util.Date"/>
<ref bean="date"/>
</array>
</property>
<property name="objectList">
<list>
<value>123</value>
<bean class="java.util.Date"/>
<ref bean="date"/>
</list>
</property>
<property name="objectSet">
<set>
<value>123</value>
<bean class="java.util.Date"/>
<ref bean="date"/>
</set>
</property>
<property name="objectMap">
<map>
<entry key="alvin" value="123"/>
<entry key-ref="date" value="123"/>
<entry key="123" value-ref="date"/>
</map>
</property>
<property name="properties">
<props>
<prop key="alvin">123</prop>
</props>
</property>
</bean>
配置实例
<!--c3p0 datasource-->
<bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/db_test?characterEncoding=utf-8"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
<!--queryRunner-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="ds"/>
</bean>
<bean id="favoriteMapper" class="com.alvin.mapper.impl.FavoriteMapperImpl">
<property name="queryRunner" ref="queryRunner"/>
</bean>
<bean id="favoriteService" class="com.alvin.service.impl.FavoriteServiceImpl">
<property name="favoriteMapper" ref="favoriteMapper"/>
</bean>
使用
ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("bean.xml");
User user = (User) context.getBean("user");
底层简单模拟
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class BeanFactory {
//用来加载properties配置文件的类
private static Properties props = new Properties();
//是一个容器,用来存放bean,相当于Spring IOC的核心容器
private static Map<String, Object> beans = new HashMap<String, Object>();
//使用静态代码块加载配置文件,以及实例化bean
static {
//使用类加载器获取配置文件
InputStream inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.properties");
//使用properties类加载配置文件
try {
props.load(inputStream);
//解析properties类
//获取所有的key
Set<Object> set = props.keySet();
//遍历获取到的key
for (Object key : set) {
//根据key,获取配置文件中的值
//获取到的值,就是需要实例化的全限定名例如com.alvin.driver.impl.MySQLDriver
String value = (String) props.get(key);
//使用反射的方式实例化这个bean
Object object = Class.forName(value).newInstance();
//把实例和实例对应的名字,放到容器中
beans.put(key.toString(),object);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object getBean(String name) {
return beans.get(name);
}
}
全注解方式
基础
# 创建对象
@Component
@Controller
@Service
@Repository
# 注入数据
@Autowired 按照bean的class注入
@Qualifier 按照bean的id注入
@Resource 不推荐
@Value 注入基本数据类型和 String
# 改变作用范围
@Scope bean的作用范围,取值:singleton prototype request session globalsession
# 生命周期相关
@PostConstruct 初始化方法
@PreDestroy 销毁方法
# 其他
@Configuration spring 配置类
@ComponentScan 扫描的包
@Bean 写在方法上,表明使用此方法创建一个对象
@PropertySource 加载.properties 文件中的配置
@Import 导入其他配置类
包扫描方式
配置
<context:component-scan base-package="com.alvin"/>
使用
context = new ClassPathXmlApplicationContext("annoBeans.xml");
config方式
配置
jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_test?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
config/Spring.config
@Configuration
@ComponentScan("com.alvin")
@Import(JdbcConfig.class)
public class SpringConfig {
}
config/Jdbc.config
@Configuration
@PropertySource("classpath:jdbcConfig.properties")
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public ComboPooledDataSource createDataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}
@Bean
public QueryRunner createQueryRunner() {
return new QueryRunner(createDataSource());
}
}
在impl.class中注解
@Repository
public class FavoriteMapperImpl implements FavoriteMapper {
@Autowired
private QueryRunner queryRunner;
public void setQueryRunner(QueryRunner queryRunner) {
this.queryRunner = queryRunner;
}
public List<Favorite> queryAll() throws Exception {
String sql = "select * from tab_favorite";
List<Favorite> favoriteList = queryRunner.query(sql, new BeanListHandler<Favorite>(Favorite.class));
return favoriteList;
}
}
使用
context = new AnnotationConfigApplicationContext(SpringConfig.class);
FavoriteService favoriteService = context.getBean(FavoriteService.class);
spring整合junit
引用
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
<scope>test</scope>
</dependency>
示例
import javax.annotation.Resource;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
//@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class springTest extends AbstractJUnit4SpringContextTests {
@Resource
private FavoriteService favoriteService;
@Test
public void method1() throws Exception {
List<Favorite> favorites = favoriteService.queryAll();
System.out.println(favorites);
}
}
springIOC学习笔记的更多相关文章
- spring-Ioc学习笔记
spring 是面向Bean的编程 Ioc (Inversion of Control) 控制反转/依赖注入(DI:Dependency Injection) Aop(Aspect Oriented ...
- 史上最全的SpringMVC学习笔记
SpringMVC学习笔记---- 一.SpringMVC基础入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于Spring ...
- SSM框架学习笔记_第1章_SpringIOC概述
第1章 SpringIOC概述 Spring是一个轻量级的控制反转(IOC)和面向切面(AOP)的容器框架. 1.1 控制反转IOC IOC(inversion of controller)是一种概念 ...
- js学习笔记:webpack基础入门(一)
之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...
- PHP-自定义模板-学习笔记
1. 开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2. 整体架构图 ...
- PHP-会员登录与注册例子解析-学习笔记
1.开始 最近开始学习李炎恢老师的<PHP第二季度视频>中的“章节5:使用OOP注册会员”,做一个学习笔记,通过绘制基本页面流程和UML类图,来对加深理解. 2.基本页面流程 3.通过UM ...
- 2014年暑假c#学习笔记目录
2014年暑假c#学习笔记 一.C#编程基础 1. c#编程基础之枚举 2. c#编程基础之函数可变参数 3. c#编程基础之字符串基础 4. c#编程基础之字符串函数 5.c#编程基础之ref.ou ...
- JAVA GUI编程学习笔记目录
2014年暑假JAVA GUI编程学习笔记目录 1.JAVA之GUI编程概述 2.JAVA之GUI编程布局 3.JAVA之GUI编程Frame窗口 4.JAVA之GUI编程事件监听机制 5.JAVA之 ...
- seaJs学习笔记2 – seaJs组建库的使用
原文地址:seaJs学习笔记2 – seaJs组建库的使用 我觉得学习新东西并不是会使用它就够了的,会使用仅仅代表你看懂了,理解了,二不代表你深入了,彻悟了它的精髓. 所以不断的学习将是源源不断. 最 ...
随机推荐
- 通过CGI实现在Html页面上执行shell命令
在mac上配置cgi(不用系统自带的apache cgi.) 安装cgi 1. brew update 2. brew install httpd24 安装完后,会有如下提示 DocumentRoot ...
- C# 数组基础
一.数组的基础知识 1.数组有什么用? 如果需要同一个类型的多个对象,就可以使用数组.数组是一种数组结构,它可以包含同一个类型的多个元素. 2.数组的初始化方式 第一种:先声明后赋值 ]; array ...
- First Android application
In eclipse ADT : 1.创建一个新工程 File -> New -> Android Application Project 2.三个主要的文件 /src/MainActiv ...
- 几种流行的开源WebService框架Axis1,Axis2,Xfire,CXF,JWS比较
几种流行的开源WebService框架Axis1,Axis2,Xfire,CXF,JWS比较 来源 XFire VS Axis XFire是与Axis2 并列的新一代WebService平台.之所 ...
- python-Lock锁线程同步和互斥
#!/usr/bin/python #coding=utf-8 #线程间通信的同步与互斥操作-锁 import threading a=b=0 lock=threading.Lock() def va ...
- linux centos 7.5 安装mysql5.7
1 下载tar包,这里使用wget从官网下载(注:下载地址随时可能有变动,wget命令默认下载目录为当前所在文件夹) wget https://dev.mysql.com/get/Downloads/ ...
- UVM_INFO
文件:src/ch3/section3.5/3.5.6/get/my_model.sv 21 function void my_model::build_phase(uvm_phase phase); ...
- Android Anwendungsprogramm Entwicklung
1.Einführung des Androids 1.1 Grundlage der Anwendung Activity ist eine Spezifische Bespiel von Andr ...
- The servlets named [create_subscription] and [servlet.create] are both mapped to the url-pattern [/create] which is not permitted [duplicate]
原因,代码中在public前已经有了默认的配置路径: 如: @WebServlet("/ShowUser")public class ShowUser extends HttpSe ...
- WordPress主题开发:主题初始化
在最简单的情况下,一个WordPress主题由两个文件构成: index.php ------------------主模版 style.css -------------------主样式表(注意 ...