【Spring】Spring,我的零散使用杂记
通过Java类设置配置信息,JavaConfig
Spring常用的通过XML或者@Controller、@Servoce、@Repository、@Component等注解注册Bean,最近看Spring Session的源码,知道还有JavaConfig
注册Bean的方式,就是通过@Configuration
、@Bean
注册Bean。
引用依赖包:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>
这个类是配置Bean的:
package com.nicchagil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class UserConfiguration {
@Bean
public UserService userService(UserDAO userDAO) {
return new UserService();
}
@Bean
public UserDAO userDAO() {
return new UserDAO();
}
}
这两个Bean是这样的:
package com.nicchagil;
public class UserDAO {
}
package com.nicchagil;
public class UserService {
}
这个BeanPostProcessor
是用于看Bean有没有实例化的,与JavaConfig
本身没什么关系:
package com.nicchagil;
import java.util.logging.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class MyBeanPostProcessor implements BeanPostProcessor {
Logger logger = Logger.getLogger("MyBeanPostProcessor");
public Object postProcessBeforeInitialization(Object obj, String arg1)
throws BeansException {
return obj;
}
public Object postProcessAfterInitialization(Object obj, String arg1)
throws BeansException {
if (obj != null) {
logger.info("实例化:" + obj + ", Class:" + obj.getClass().getName());
}
return obj;
}
}
记得要注册扫描包的路径:
<?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
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- scan the component from the base package -->
<context:component-scan base-package="com.nicchagil" />
<bean id="myBeanPostProcessor" class="com.nicchagil.MyBeanPostProcessor" />
</beans>
测试类:
package com.nicchagil;
import java.util.logging.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HowToUse {
public static Logger LOGGER = Logger.getLogger("HowToUse");
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("spring.xml");
UserDAO userDAO = context.getBean("userDAO", UserDAO.class);
LOGGER.info("userDAO : " + userDAO);
UserService userService = context.getBean("userService", UserService.class);
LOGGER.info("userService : " + userService);
}
}
运行日志:
六月 11, 2017 3:41:57 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@37f8bb67: startup date [Sun Jun 11 15:41:57 CST 2017]; root of context hierarchy
六月 11, 2017 3:41:57 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [spring.xml]
六月 11, 2017 3:41:58 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@1d057a39: defining beans [userConfiguration,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,myBeanPostProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor,userService,userDAO]; root of factory hierarchy
六月 11, 2017 3:41:58 下午 com.nicchagil.MyBeanPostProcessor postProcessAfterInitialization
信息: 实例化:com.nicchagil.UserConfiguration$$EnhancerBySpringCGLIB$$cd2ac8bb@32eebfca, Class:com.nicchagil.UserConfiguration$$EnhancerBySpringCGLIB$$cd2ac8bb
六月 11, 2017 3:41:58 下午 com.nicchagil.MyBeanPostProcessor postProcessAfterInitialization
信息: 实例化:com.nicchagil.UserDAO@47db50c5, Class:com.nicchagil.UserDAO
六月 11, 2017 3:41:58 下午 com.nicchagil.MyBeanPostProcessor postProcessAfterInitialization
信息: 实例化:com.nicchagil.UserService@149494d8, Class:com.nicchagil.UserService
六月 11, 2017 3:41:58 下午 com.nicchagil.HowToUse main
信息: userDAO : com.nicchagil.UserDAO@47db50c5
六月 11, 2017 3:41:58 下午 com.nicchagil.HowToUse main
信息: userService : com.nicchagil.UserService@149494d8
自定义逻辑创建Bean的工厂Bean,FactoryBean
引入POM:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.10.RELEASE</version>
</dependency>
声明实体:
package com.nicchagil.factorybeanexercise;
public class User {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
}
定义工厂:
package com.nicchagil.factorybeanexercise;
import org.springframework.beans.factory.FactoryBean;
public class UserFactoryBean implements FactoryBean<User> {
/**
* 获取对象
*/
@Override
public User getObject() throws Exception {
User user = new User();
user.setId(123);
user.setName("Nick Huang");
return user;
}
/**
* 获取对象的类型
*/
@Override
public Class<?> getObjectType() {
return User.class;
}
/**
* 对象是否单例
*/
@Override
public boolean isSingleton() {
return true;
}
}
注册工厂:
<?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
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="user" class="com.nicchagil.factorybeanexercise.UserFactoryBean" />
</beans>
测试类:
package com.nicchagil.factorybeanexercise;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HowToTest {
public static void main(String[] args) {
@SuppressWarnings("resource")
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
User user = ac.getBean("user", User.class);
System.out.println(user);
}
}
【Spring】Spring,我的零散使用杂记的更多相关文章
- spring spring data jpa save操作事务
整合spring spring data jpa的时候,在save方法上加了@Transactional注解.此时调用springdatajpa save方法并不会真的把数据提交给数据库,而是缓存起来 ...
- 基于Spring + Spring MVC + Mybatis + shiro 高性能web构建
一直想写这篇文章,前段时间 痴迷于JavaScript.NodeJs.AngularJS,做了大量的研究,对前后端交互有了更深层次的认识. 今天抽个时间写这篇文章,我有预感,这将是一篇很详细的文章,详 ...
- spring + spring mvc + mybatis + react + reflux + webpack Web工程例子
前言 最近写了个Java Web工程demo,使用maven构建: 后端使用spring + spring mvc + mybatis: 前端使用react + react-router+ webpa ...
- [转]基于Spring + Spring MVC + Mybatis 高性能web构建
http://blog.csdn.net/zoutongyuan/article/details/41379851/ 一直想写这篇文章,前段时间 痴迷于JavaScript.NodeJs.Angula ...
- Spring+Spring MVC+MyBatis
Spring+Spring MVC+MyBatis 目录 一.新建一个基于Maven的Web项目 二.创建数据库与表 三.添加依赖包 四.新建POJO实体层 五.新建MyBatis SQL映射层 六. ...
- MyBatis+Spring+Spring MVC整合开发
MyBatis+Spring+Spring MVC整合开发课程观看地址:http://www.xuetuwuyou.com/course/65课程出自学途无忧网:http://www.xuetuwuy ...
- 基于Spring + Spring MVC + Mybatis 高性能web构建
基于Spring + Spring MVC + Mybatis 高性能web构建 一直想写这篇文章,前段时间 痴迷于JavaScript.NodeJs.AngularJs,做了大量的研究,对前后端交互 ...
- maven/eclipse搭建ssm(spring+spring mvc+mybatis)
maven/eclipse搭建ssm(spring+spring mvc+mybatis) 前言 本文旨在利用maven搭建ssm环境,而关于maven的具体内容,大家可以去阅读<Maven 实 ...
- Spring + Spring MVC + Hibernate
Spring + Spring MVC + Hibernate项目开发集成(注解) Posted on 2015-05-09 11:58 沐浴未来的我和你 阅读(307) 评论(0) 编辑 收藏 在自 ...
随机推荐
- Asp.Net通过ODBC连接Oracle数据库
本来有个项目是通过安装Oracle client然后让asp.net引用System.Data.OracleClient来访问Oracle数据库的,但是不知道为什么老是报:ORA-12170:连接超时 ...
- C#中巧用#if DEBUG 进行调试
#if DEBUG是个好东西. #if DEBUG UserID = "abc@test.com"; Password = "; #endif 当调试代码的时候加上适当的 ...
- PHP哈希表碰撞攻击
哈希表是一种查找效率极高的数据结构,PHP中的哈希表是一种极为重要的数据结构,不但用于表示数组,关联数组,对象属性,函数表,符号表,还在Zend虚拟机内部用于存储上下文环境信息(执行上下文的变量及函数 ...
- windows 7 提示缺少D3DCOMPILER_47.dll的正确解决方法
下载 KB4019990补丁 我上传一下吧. 点击下载
- [转]NLP数据集
原文链接 nlp-datasets Alphabetical list of free/public domain datasets with text data for use in Natural ...
- RHEL/CentOS 7.x/6.x/5.x开启EPEL仓库
说明 原文链接 翻译:@adolphlwq 项目地址 这篇指南文章教你如何在 RHEL/CentOS 7.x/6.x/5.x 系统中开启EPEL仓库支持,以便你可以使用 yum 命令 安装额外的标准开 ...
- Git 撤消操作(分布式版本控制系统)
1.覆盖提交 有时候我们提交完了才发现漏掉了几个文件没有添加,或者提交信息写错了.此时,可以运行带有 --amend 选项的提交命令尝试重新提交. $ git commit --amend 或 # g ...
- 【Linux】字符转换命令col
[root@www ~]# col [-xb] 选项与参数: -x :将 tab 键转换成对等的空格键 -b :过滤掉所有的控制字符,包括RLF(Reverse Line Feed)和HRF(Halt ...
- virtualbox主机与虚拟机互访,虚拟机上网
实现virtualbox主机与虚拟机互访,同时虚拟机还可以上网: 主要通过配置两块网卡来实现: 1,先配置好一台虚拟机Slave1,这里使用CentOS : 2,使用VirtualBox复制这台虚拟机 ...
- Android KLog源代码分析
Android KLog源代码分析 Android KLog源代码分析 代码结构 详细分析 BaseLog FileLog JsonLog XmlLog 核心文件KLogjava分析 遇到的问题 一直 ...