spring IoC (IDEA)—— 声明和获取Bean

1、声明一个Bean

    <bean id="s1" name="student,stu" class="com.etc.entity.Student">

2、获取bean

方式1(根据id来获取,常用,但需要类型强转)

        Student student1 = (Student) context.getBean("s1");

方式2(根据id来获取,常用,不需要进行类型强转)

        Student student2 = context.getBean("s1",Student.class);

方式3(根据name来获取,不推荐)

        Student student3 = context.getBean("student",Student.class);
        Student student4 = context.getBean("stu",Student.class);

3、Bean的作用域

什么是作用域呢?即“scope”,在面向对象程序设计中一般指对象或变量之间的可见范围。而在Spring容器中是指其创建的Bean对象相对于其他Bean对象的请求可见范围。

Spring提供“singleton”和“prototype”两种基本作用域,另外提供“request”、“session”、“global session”三种web作用域;Spring还允许用户定制自己的作用域。

利用<bean>标签中的scope属性来指定:

scope值:

lsingleton单例:每次取出的bean都是同一个bean。默认就是这个

lprototype原型:每次取的bean时,都会重新创建一个新的bean,是懒加载。

lrequest:一次请求一个bean定义对应一个实例(web相关)

lsession:一个session定义对应一个实例(web相关)

lglobalsession类似于session作用域,只是其用于portlet环境的web应用。如果在非portlet环境将视为session作用域(web相关)。

实现scope中可以选择request或者session

在pom中增加以下依赖:

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>4.3.18.RELEASE</version>
</dependency>

在web.xml中增加监听器配置:

<listener>
  <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

猜你喜欢

转载自blog.csdn.net/Milan__Kundera/article/details/82526185
今日推荐