什么是Spring中的Bean
- 如果把Spring看作一个大工厂,则Spring容器中的Bean就是该工厂的产品。使用时需在配置文件中告诉需要哪些Bean,以及用何种方式将这些Bean装配在一起。Bean的本质就是java中的类,而Spring中的Bean就是对实体类的引用,来生产java类对象。
Bean的作用域
- singleton作用域
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="命名" class="权限类全名" scope="sinleton"/>
- prototype作用域
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="命名" class="权限类全名" scope="prototype"/>
基于XMl的配置
-
构造方式注入方式装配User案例
<bean id="user1" class="权限类的全名"> <constructor-arg index="0" value="tom" /> <constructor-arg index="1" value="123" /> </bean>
-
使用设值注入方式配置User案例
<bean id="user1" class="权限类的全名">
<property name="username" value="tom" />
<property name="password" value="123" />
</bean>
基于Annotation(注解)的装配
- XMl文件的配置
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!--使用context空间,通知Spring扫描指定包下所有的Bean类,进行注解解析-->
<context:component-scan base-package="需要对注解进行解析的包全名" />
自动装配
- 自动装配事例
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="userDao" class="类的接口全名"></bean>
<bean id="userSevice" class="类的接口全名" autowire="byName"></bean>
<bean id="userController" class="类的全名" autowire="byName"></bean>