002-Spring4 快速入门-项目搭建、基于注解的开发bean,Bean创建和装配、基于注解的开发bean,Bean初始化销毁、Bean装配,注解、Bean依赖注入
一、项目搭建
1、项目创建
eclipse→project explorer→new→Project→Maven Project
默认配置即可创建项目
2、spring配置
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
3、配置项目编译目标版本
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
在项目上右键→maven→update project即可
二、基于注解的开发bean,Bean创建和装配
1、增加配置类,创建Bean
方法一、创建bean
增加注解@Configuration、@Bean、@Scope
@Configuration
public class MyConfig {
@Bean(name="myBean")
@Scope("prototype")
public MyBean createMyBean() {
return new MyBean();
}
}
方法二、使用FactoryBean创建,lambda方式
public class RunnableFactoryBean implements FactoryBean<Runnable>{
@Override
public Runnable getObject() throws Exception {
return ()->{};
}
@Override
public Class<?> getObjectType() {
return Runnable.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
如定义一个Jeep,讲工厂类改成
public class RunnableFactoryBean implements FactoryBean<Jeep>{
@Override
public Jeep getObject() throws Exception {
return new Jeep();
}
@Override
public Class<?> getObjectType() {
return Jeep.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
使用即可。
方法三、需要参数,默认会获取,自动注入
创建class Car
创建一个工厂
public class CarFactory {
public Car create() {
return new Car();
}
}
在Config中添加
@Bean
public CarFactory createCarFactory() {
return new CarFactory();
} @Bean
public Car createCar(CarFactory factory) {
return factory.create();
}
使用即可:System.out.println(annotationConfigApplicationContext.getBean(Car.class));//名称获取
2、在方法入口增加配置
方法一、配置一个或多个指定的类型
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
方法二、配置指定扫描的包
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("com.lhx.spring.spring");
方法三、配置指定包,并且排除
@ComponentScan(basePackages="com.lhx.spring.spring",excludeFilters=@Filter(type=FilterType.ASSIGNABLE_TYPE))
FilterType有五种类型
ANNOTATION、ASSIGNABLE_TYPE、ASPECTJ、REGEX、CUSTOM
使用
建一个Dog类
public class Dog {
public void init() {
System.out.println("--------init------");
}
public void destory() {
System.out.println("--------destory------");
}
}
增加一个DogConfig配置类
@Configuration
public class DogConfig { @Bean(initMethod = "init", destroyMethod = "destory")
public Dog createDog() {
return new Dog();
}
}
增加一个扫描配置类
@ComponentScan(basePackages="com.lhx.spring.spring",excludeFilters=@Filter(type=FilterType.ASSIGNABLE_TYPE,classes=DogConfig.class))
@Configuration
public class AnnotationScan { }
当然也可以直接指定有注解的类类型,如UserController.class
使用
public class AnnotationClient2 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnnotationScan.class);
System.out.println(context.getBean(Car.class));
System.out.println(context.getBean(Cat.class));
System.out.println(context.getBean(Dog.class));
System.out.println(context.getBean(Animal.class));
System.out.println(context.getBean(User.class));
context.close();
}
}
3、获取Bean
3.1、根据类型获取
System.out.println(annotationConfigApplicationContext.getBean(MyBean.class));
3.2、根据名称获取
System.out.println(annotationConfigApplicationContext.getBean("createMyBean"));//默认是方法名
注意:默认是1中配置的方法名
也可以再注解Bean中指定:@Bean(name="myBean"),指定后默认方法名不能使用
System.out.println(annotationConfigApplicationContext.getBean("myBean"));// 指定具体名
其中:默认是单例,@Scope("prototype") 非单例了
如1,方法二、展示
System.out.println(annotationConfigApplicationContext.getBean(Jeep.class));
System.out.println(annotationConfigApplicationContext.getBean("createRunnableFactoryBean"));
这个是具体的bean,如何获取工程bean
System.out.println(annotationConfigApplicationContext.getBean(RunnableFactoryBean.class));//类型获取
System.out.println(annotationConfigApplicationContext.getBean("&createRunnableFactoryBean"));//名称获取
&能获取原因:AnnotationConfigApplicationContext→GenericApplicationContext→AbstractApplicationContext→
ConfigurableApplicationContext→ApplicationContext→ListableBeanFactory→BeanFactory

三、基于注解的开发bean,Bean初始化销毁
1、初始化实现InitializingBean,销毁实现DisposableBean
public class Cat implements InitializingBean,DisposableBean{
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("----------afterPropertiesSet--------");
}
@Override
public void destroy() throws Exception {
System.out.println("----------destroy--------");
}
}
2、注入时候实现,
在类中顶一个init,destory,在Config配置中@Bean配置;
@Bean(initMethod="init",destroyMethod="destory")
public Dog createDog() {
return new Dog();
}
3、使用java中,jsr250提供的注解,@PostConstruct,@PreDestroy
public class Animal {
@PostConstruct
public void initial() {
System.out.println("--------initial------");
}
@PreDestroy
public void close() {
System.out.println("--------close------");
}
}
四、Bean装配,注解
1、使用@Component注解,没有明确角色
在class 上增加@Component注解,在AnnotationConfigApplicationContext,参数中添加即可。
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(
MyConfig.class,User.class);
使用即可。注意:没法绑定初始化方法等。
System.out.println(annotationConfigApplicationContext.getBean(User.class));
System.out.println(annotationConfigApplicationContext.getBean("user"));
可以通过getBeansOfType获取类型Map
System.out.println(annotationConfigApplicationContext.getBeansOfType(User.class));
{user=com.lhx.spring.spring.User@5e57643e}
如果在通过Config注入,那么获取时候不能使用类型获取了,有多个不知道创建那个,可以使用名称获取
2、可以使用其他注解
@Repository 一般用在数据访问层
@Service 一般用在Service层
@Controller 一般用在控制层
五、Bean依赖注入
5.1、Spring方式,@Autowired
@Autowired
private UserDao userDao;
如果有多个
1、名称方式,可以使用getBeansOfType获取名称,然后指定名称注入
@Autowired
@Qualifier("userDao")
private UserDao userDao;
2、在其中某个增加@Primary,默认就会找这个。
5.2、jsr 250 方式,@Resource
5.3、jsr 330方式,@Inject
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
代码地址:https://github.com/bjlhx15/spring-boot.git
002-Spring4 快速入门-项目搭建、基于注解的开发bean,Bean创建和装配、基于注解的开发bean,Bean初始化销毁、Bean装配,注解、Bean依赖注入的更多相关文章
- 004-Spring boot 快速入门-项目搭建与启动、SpringBootApplication、启动图标
一.官方地址 Spring:http://spring.io/ Spring Project:http://spring.io/projects Spring boot:https://project ...
- 基于renren-fast的快速入门项目实战(实现报表增删改查)
基于renren-fast的快速入门项目实战(实现报表增删改查) 说明:renren-fast是一个开源的基于springboot的前后端分离手脚架,当前版本是3.0 官方开发文档需付费,对于新手而言 ...
- Spring4 快速入门
Spring4 快速入门 1 Spring简介 1.1 Spring是什么? Spring 是一个 IOC 和 AOP 容器的开源框架,为简化企业级应用而生. IOC(Inversion of Con ...
- 架构师入门:搭建双注册中心的高可用Eureka架构(基于项目实战)
本文的案例是基于 架构师入门:搭建基本的Eureka架构(从项目里抽取) 改写的. 在上文里,我们演示Eureka客户端调用服务的整个流程,在这部分里我们将在架构上有所改进.大家可以想象下,在上文里案 ...
- ELK系列(1) - Elasticsearch + Logstash + Kibana + Log4j2快速入门与搭建用例
前言 最近公司分了个ELK相关的任务给我,在一边学习一边工作之余,总结下这些天来的学习历程和踩坑记录. 首先介绍下使用ELK的项目背景:在项目的数据库里有个表用来存储消息队列的消费日志,这些日志用于开 ...
- Activiti快速入门项目-kft-activiti-demo
1.项目简介 1.1 项目信息 本项目旨在让Activiti初学者可以快速入门,使用工作流里面的请假流程作为Activiti企业实战的Hello World. 简单通过这个实例说明如何结合流程与业务, ...
- SPRING-BOOT系列之Spring4快速入门
上节 : spring boot简介 接着上章节的spring boot简介,我们会发现boot是基于spring的,其中最重要的就是spring容器了.那么本章着重介绍spring容器装配自定义be ...
- eslint 入门项目搭建过程
github 地址 : https://github.com/gebin/eslint-demo 运行该项目 npm install npm start 访问 http://localhost:900 ...
- Vue -cli 入门 --项目搭建(一)
一. 安装node.js环境. 在node.js官网下载稳定版本(https://nodejs.org/en/) 下载完成后点击安装,安装过程很简单,一直next即可,安装完成会自动添加node及np ...
随机推荐
- PHP 中一个 False 引发的问题,差点让公司损失一百万
PHP 中一个 False 引发的问题,差点让公司损失一百万 一.场景描述 上周我一个在金融公司的同学,他在线上写一个 Bug,差点造成公司损失百万.幸好他及时发现了这个问题并修复了.这是一个由 PH ...
- linux(centeros)svn的安装
SVN linux搭建svn服务器参考:http://www.cnblogs.com/chaichuan/p/3758173.htmlSubversion(SVN) 是一个开源的版本控制系統, 也就是 ...
- PHP至Document类操作 xml 文件
今天将项目上传到服务器后,打开项目发现报错 Error:undefined function appendChild()......, 根据提示查看源代码,发现 new Document()-> ...
- 【问题解决方案】CentOS7替换yum的问题:使用yum makecache出现File contains no section headers
参考链接 CentOS7替换yum的问题:使用yum时出现File contains no section headers centos安装网络repo源及错误说明 一.centos替换yum的步骤 ...
- nginx配置反向代理,解决前端开发的跨域问题
适用:开发和生产环境 配置如下 server { listen 10901; server_name res.pre.ices.red; #charset koi8-r; #access_log lo ...
- HTML A标签 href click事件冲突
转自:https://blog.csdn.net/xinglu/article/details/45199337
- Mybatis驼峰式命名
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC ...
- 安装sysbench,报错"Could not resolve 'ports.ubuntu.com'"
在ubuntu系统中安装sysbench时报错“Could not resolve 'ports.ubuntu.com'”怎么办呢? 安装时报错: 亲测可用的方法: 修改 resolv.conf 文件 ...
- Linux架构之Nginx 高可用
第53章 Nginx之高可用Keepalived 一.Keepalived高可用基本概述 1.1)什么是高可用 一般是指2台机器启动着完全相同的业务系统,当有一台机器down机了,另外一台服务器就能快 ...
- 02 getsockopt
#include <sys/types.h> /* See NOTES */ #include <sys/socket.h> int getsockopt(int sockfd ...