【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) 编辑 收藏 在自 ...
随机推荐
- ios中tableview的移动添加删除
// // MJViewController.m // UITableView-编辑模式 // // Created by mj on 13-4-11. // Copyright (c) 2013年 ...
- 转 一台电脑安装多个tomcat
只要改这一个就可以了.port 改成8081即可.<Connector port="8081" protocol="HTTP/1.1" connectio ...
- 【LeetCode】Binary Tree Upside Down
Binary Tree Upside Down Given a binary tree where all the right nodes are either leaf nodes with a s ...
- php使用wkhtmltopdf导出pdf
参考:史上最强php生成pdf文件,html转pdf文件方法 http://biostall.com/wkhtmltopdf-add-header-footer-to-only-first-last- ...
- Apache Rewrite(大小写)
1.Rewrite规则简介: Rewirte 主要的功能就是实现URL的跳转,它的正则表达式是基于Perl语言.可基于服务器级的(httpd.conf)和目录级的 (.htaccess)两种方式.如果 ...
- opencv 摄像头 线程
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <pthread.h> ...
- Android--------从一个包中的Avtivity创建另外另外一个包的Context
Android中有Context的概念,想必大家都知道.Context可以做很多事情,打开activity.发送广播.打开本包下文件夹和数据库.获取classLoader.获取资源等等.如果我们得到了 ...
- elasticsearch实现按天翻滚索引
最近在做集中式日志,将应用的日志保存到Elasticsearch中,结合kibana实现集中化日志监控和报警.在设计ES存储的时候.考虑到日志的特殊性,打算采用Daily Indices方式.名称为: ...
- apktool 在mac下的使用 -反编译安卓apk文件
1.下载apktool 点击这里下载 ,里面有两个文件,一个是.jar,一个是自己写的脚本.sh 注:最新的apktool.jar 文件可以点击这里下载 .sh脚本是自写脚本可不用更新最新,下载的ja ...
- python 实验环境
python 实验环境的搭建 刚开始在windows环境下尝试过komodo ,eclispse pydev,swing,spyder甚至limodou的编辑器,之后ipython,安装很多科学计算包 ...