第一种使用@Bean的方式

1、创建一个bean

package com.springbean;

public class Person {

    private  String name;
private Integer age ; public Person(String name, Integer age) {
this.name = name;
this.age = age;
} public void setName(String name) {
this.name = name;
} public void setAge(Integer age) {
this.age = age;
} public String getName() {
return name;
} public Integer getAge() {
return age;
} @Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2、创建配置类:

import com.springbean.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; @Configuration
public class PersonConfig { @Bean
  //@Bean("myperson") 这是设置bean的名字
public Person person(){
   System.out.println("已经创建实例");
   return new Person("张三",20); } }

3、测试
import com.spring.config.PersonConfig;
import com.springbean.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class ApplicationTest {
public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
Person bean = applicationContext.getBean(Person.class);
System.out.println(bean);     //获取bean的类型,默认是方法名,需要修改就在配置类中@Bean里面加上名字
    String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
    for (String beanType : beanNamesForType){
    System.out.println(beanType);
    }
  } 
}
和xml配置文件一样,默认的bean是单例的,如果需要改变为prototype,xml配置文件里是加上scope="prototype",这里PersonConfig配置类中需要加上注解@Scope("prototype")。
介绍一下bean的几种类型的作用域。
  • singleton:单实例(默认),ioc容器启动时就会创建对象放到ioc容器中,以后每次获取都是直接从ioc容器中获取,ioc容器可以简单理解为map
  • prototype:多实例(原型),ioc容器启动并不会去调用方法创建对象,而是每次我们获取对象的时候,才会调用方法去创建。
  • requst:同一次请求创建一个实例
  • session:同一个session创建一个实例
不加注解测试:
 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
Person bean = applicationContext.getBean(Person.class);
Person bean2 = applicationContext.getBean(Person.class);
System.out.println(bean==bean2);
//打印结果为true

加上注解@Scope("prototype")测试:

 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
Person bean = applicationContext.getBean(Person.class);
Person bean2 = applicationContext.getBean(Person.class);
System.out.println(bean==bean2);
//打印结果为fale

我们也可以改变单例时ioc加载的时候就创建实例,只要在我们的PersonConfig配置类中加上@Lazy注解,使用懒加载。测试

public class ApplicationTest {
public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
/* Person bean = applicationContext.getBean(Person.class);
Person bean2 = applicationContext.getBean(Person.class);
System.out.println(bean==bean2);*/
    /*
String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class);
for (String beanType : beanNamesForType){
System.out.println(beanType);
}*/
}
}

这是时打印栏将不会打印出“已经创建实例”,就实现的单例情况下的懒加载。

第二种使用@import注解的方式

新建一个student类

public class Student {
}

在配置类PersonConfig上使用@Import注解,这里面可以传入一个数组,用大括号{}

@Configuration
@Import({Student.class})
public class PersonConfig {

测试:

public class DemoTest {

    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);

    @Test
public void test(){ Student bean = applicationContext.getBean(Student.class);
System.out.println(bean); }
}

打印结果:com.springbean.Student@2c34f934 ,注入成功

还可以在@Import中加入ImportSelector的实现类来实现bean的注入

创建Parent和Teacher类

public class Parent {
} public class Teacher {
}

创建ImportSelector的实现类MyImportSelector,返回需要注入的bean,这里是全类名

public class myImportSelector implements ImportSelector{
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) { return new String[]{"com.springbean.Parent","com.springbean.Teacher"};
}
}

修改PersonConfig,这里传入实现类MyImportSelector

@Configuration
@Import({Student.class, myImportSelector.class})
public class PersonConfig {

测试:

     Parent parent = applicationContext.getBean(Parent.class);
Teacher teacher = applicationContext.getBean(Teacher.class);
System.out.println(parent);
System.out.println(teacher);

打印结果:

com.springbean.Parent@3b2cf7ab
com.springbean.Teacher@2aa5fe93

 

 第三种使用@ComponentScan的方式:

@Configuration
@ComponentScan("com.springbean")
public class MainBeanConfig { }

指定需要扫描包的路径,相应的类中加上组件注解。

												

spring使用注解的方式创建bean ,将组件加入容器中的更多相关文章

  1. 三种方式创建bean对象在springIOC容器中初始化、销毁阶段要调用的自定义方法

    1. 使用@Bean注解定义initMethod和destroyMethod 所谓initMethod和destroyMethod,是指在springIOC容器中,对于bean对象执行到初始化阶段和销 ...

  2. SSH(Struts2+Spring+Hibernate)框架搭建流程<注解的方式创建Bean>

    此篇讲的是MyEclipse9工具提供的支持搭建自加包有代码也是相同:用户登录与注册的例子,表字段只有name,password. SSH,xml方式搭建文章链接地址:http://www.cnblo ...

  3. sping练习,在Eclipse搭建的Spring开发环境中,使用工厂方式创建Bean对象,将创建的Bean对象输出到控制台。

    相关 知识 >>> 相关 练习 >>> 实现要求: 在Eclipse搭建的Spring开发环境中,使用工厂方式创建Bean对象,将创建的Bean对象输出到控制台.要 ...

  4. 跟着刚哥学习Spring框架--通过XML方式配置Bean(三)

    Spring配置Bean有两种形式(XML和注解) 今天我们学习通过XML方式配置Bean 1. Bean的配置方式 通过全类名(反射)的方式   √ id:标识容器中的bean.id唯一. √ cl ...

  5. 基于注解的方式管理Bean

    --------------------siwuxie095                                 基于注解的方式管理 Bean         (一)准备         ...

  6. Spring工厂方式创建Bean实例

    创建Bean实例的方式: 1) 通过构造器(有参或无参) 方式: <bean id="" class=""/> 2) 通过静态工厂方法 方式: &l ...

  7. 7 -- Spring的基本用法 -- 7... 创建Bean的3种方式

    7.7 创建Bean的3种方式 ① 调用构造器创建Bean. ② 调用静态工厂方法创建Bean. ③ 调用实例工厂方法创建Bean. 7.7.1 使用构造器创建Bean实例. 使用构造器来创建Bean ...

  8. Spring Boot 使用Java代码创建Bean并注册到Spring中

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/catoop/article/details/50558333 声明同一个类下的多个实例: packa ...

  9. Spring Boot 使用Java代码创建Bean并注冊到Spring中

    从 Spring3.0 開始,添加了一种新的途经来配置Bean Definition,这就是通过 Java Code 配置 Bean Definition. 与Xml和Annotation两种配置方式 ...

随机推荐

  1. BZOJ 3218 A + B Problem (可持久化线段树+最小割)

    做法见dalao博客 geng4512的博客, 思路就是用线段树上的结点来进行区间连边.因为有一个只能往前面连的限制,所以还要可持久化.(duliu) 一直以来我都是写dinicdinicdinic做 ...

  2. harbor1.9仓库同步迁移

    harbor 1.9 实战的仓库迁移,过程实际上就是从A push 到B.16个tag 不到100G,挺快的 1分钟多. 假设我们从A迁移到B. 1.先在A上面建立一个目标仓库.    

  3. 【leetcode】1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold

    题目如下: Given a m x n matrix mat and an integer threshold. Return the maximum side-length of a square ...

  4. SIGAI机器学习第八集 数据降维1

    讲授数据降维原理,PCA的核心思想,计算投影矩阵,投影算法的完整流程,非线性降维技术,流行学习的概念,局部线性嵌入,拉普拉斯特征映射,局部保持投影,等距映射,实际应用 大纲: 数据降维问题PCA的思想 ...

  5. scrapy 4 学习 crawl spider

    前情提要: 一:图片懒加载(面对图片懒加载怎么办) ---用selenium设置图片加载的位置 --- 分析懒加载的属性,直接获取 二: 如何提高scrapy的爬取效率 增加并发:默认scrapy开启 ...

  6. 参数类型 (Mapper.java)常用

    UserBaseInfo selectByMobile(@Param("mobile")String mobile,@Param("isDeleted")Int ...

  7. 【线性代数】7-2:线性变化的矩阵(The Matrix of a Linear Transformation)

    title: [线性代数]7-2:线性变化的矩阵(The Matrix of a Linear Transformation) categories: Mathematic Linear Algebr ...

  8. Liunx之基础学习

    用户提权命令之-sudo sudo命令用来以其他身份来执行命令,预设的身份为root.在/etc/sudoers中设置了可执行sudo指令的用户.若其未经授权的用户企图使用sudo,则会发出警告的邮件 ...

  9. hdu6736(寻找最小环)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=6736 题意: 在给定图中寻找所有最小环 保证不存在一条边经过两个简单环 数据范围: $1\leq n ...

  10. PKUSC2019划水记

    Day -3~Day -2 划了两天的水,考了两次IOI赛制,垫了两次底.... 怕不是要凉啊(安慰自己才C3还有时间) Day -1 坐火车了,差点把身份证弄丢. 睡了一觉,肝了你的名字(结局草率差 ...