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组建库的使用 我觉得学习新东西并不是会使用它就够了的,会使用仅仅代表你看懂了,理解了,二不代表你深入了,彻悟了它的精髓. 所以不断的学习将是源源不断. 最 ...
随机推荐
- 开源项目-Aiguille
项目地址: https://github.com/wwkai555/Aiguille 这个项目主要使用Android L新特性 - 最新的widget以及一些值得推荐和使用的开源库比如butt ...
- Java集合类中的Iterator和ListIterator的区别
注意:内容来自网络他人文章! 最近看到集合类,知道凡是实现了Collection接口的集合类,都有一个Iterator方法,用于返回一个实现了Iterator接口的对象,用于遍历集合:(Iterato ...
- 手机端全局样式表整理(mobile)
@charset "utf-8";/* * filename: global.css * description: 全局样式(包含样式重置,公共常用 ...
- 【es6】数组扩展
只有一个参数,为数组中的值.
- windows7用WMware安装Linux虚拟机详细步骤
一.安装环境 windows7操作系统物理机VMware Workstation 软件(可以在网上下载)CentOS6.5镜像文件(其他版本都大同小异,这里以CentOS6.5为例)Cnetos6.5 ...
- JavaScript设计模式-13.组合模式
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- Spring声明式事务为何不回滚
- 深入理解java集合框架之---------Arraylist集合 -----构造函数
ArrayList有三个构造方法 ArrayList有三个常量 1.private transient Object[] elementData (数组); 2.private int size (元 ...
- gcc对open(2)支持重载吗
在Linux中,如果man -s2 open, 我们看到两种不同的函数原型声明: $ man -s2 open NAME open, creat - open and possibly create ...
- cnblog博客停用
本博客从今日起停止更新,后续的文章将会发布在新的博客mrbackkom.github.io