spring bean的介绍以及xml和注解的配置方法
5.Bean
Bean的生命周期
Bean的自动装配
Resources和ResourceLoader
5.1Bean容器的初始化
Bean容器的初始化
两个基础包:
org.springframework.beans
org.springframework.context
BeanFactory提供配置结构和基本功能,加载并初始化Bean
ApplicationContext保存了Bean对象并在spring中被广泛使用
集中常用的使用场景:
常用的文件初始化方式:
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("F:/workspace/appcontext.xml");
ApplicationContext ac = new ClassPathXmlApplicationContext("com/xxx/spring/chap1/coll.xml");
BeanFactory factory = new ClassPathXmlApplicationContext("com/xxxspring/chap1/ioc.xml");
1.在webapp中的我们一般配置到web.xml文件中
1 <!-- 配置contextConfigLocation指定spring将要使用的配置文件 -->
2 <context-param>
3 <param-name>contextConfigLocation</param-name>
4 <param-value>classpath:action.xml,classpath:dao.xml,classpath:service.xml</param-value>
5 </context-param>
6 <!-- 配置listner让spring读取配置文件-->
7 <listener>
8 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
9 </listener>
2.load-on-startup标签指定启动顺序,1为指在启动服务器的时候初始化容器
1 <listener>
2 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
3 </listener>
4
5 <servlet>
6 <servlet-name>remoting</servlet-name>
7 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
8 <init-param>
9 <param-name>contextConfigLocation</param-name>
10 <param-value>classpath:spring-remoting-servlet.xml</param-value>
11 </init-param>
12 <load-on-startup>1</load-on-startup>
13 </servlet>
3Bean的两种注入方式
a.设置值注入
b.构造注入
设置值注入案例:
基本类型的注入: 通过<property name="属性名", value="属性值/">为对应类对象初始化的值,这种方式必须在类中为对应的属性提供getxxx,setxx方法
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
6 <bean name="user,user2" class="com.xxx.spring.ioc.bean.User">
7 <property name="id" value="1"/>
8 <property name="name" value="tom"/>
9 <property name="age" value="20"/>
10 <property name="gender" value="male"/>
11 </bean>
12 </beans>
引用类型的注入:<property name="属性名" ref="引用的bean"></property>,被引入的bean和引入处可以不在同一个xml文件中,因为所有bean都会被容器初始化并保存到容器中
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
6 <bean name="memberService" class="com.xxx.run.service.impl.IMemberServiceImpl">
7 <property name="memberDao" ref="memberDao"></property>
8 </bean>
9 <bean name="memberDao" class="com.xxx.run.dao.impl.IMemberDaoImpl"></bean>
10 </beans>
构造注入
顾名思义,使用构造器对对象的初始化注入对应的值,实现方式有如下3种
1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.springframework.org/schema/beans
5 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
6 <bean name="teacher" class="com.xxx.spring.ioc.bean.Teacher">
7 <!-- 1.按照属性名赋值 ,调用有参数的构造器,顺序是参数顺序-->
8 <constructor-arg name="id" value="1"/> <!-- person(int id,String name, String gender) -->
9 <constructor-arg name="name" value="tom"/>
10 <constructor-arg name="gender" value="male"/>
11 <!-- 2.index从0开始,按照属性在构造器中出现的顺序赋值 索引值是构造器中的属性顺序 -->
12 <!-- <constructor-arg index="0" value="2"/>
13 <constructor-arg index="1" value="jack"/>
14 <constructor-arg index="2" value="male"/> -->
15 <!-- 3.按照类型进行赋值,如果出现相同的类型,按照属性在构造器中出现的顺序进行复制 -->
16 <!--<constructor-arg type="int" value="3"/>
17 <constructor-arg type="String" value="rose"/>
18 <constructor-arg type="String" value="female"/> -->
19 </bean>
20 </beans>
Teacher.java
1 public class Teacher implements Serializable{
2 private static final long serialVersionUID = 1L;
3 private int id;
4 private String name;
5 private String gender;
6
7 public Teacher(int id, String name, String gender) {
8 super();
9 this.id = id;
10 this.name = name;
11 this.gender = gender;
12 }
13
14 @Override
15 public String toString() {
16 return "Teacher [id=" + id + ", name=" + name + ", gender=" + gender
17 + "]";
18 }
19 }
测试
1 @Test
2 public void test3() throws Exception {
3 ApplicationContext ac = new ClassPathXmlApplicationContext("com/xxx/spring/chap1/constructor.xml");
4 Teacher teacher = (Teacher) ac.getBean("teacher");
5 System.out.println(teacher);//Teacher [id=1, name=tom, gender=male]
6 }
5.2Bean的生命周期
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware; public class Life implements BeanNameAware,BeanFactoryAware{
private String name; public Life(){//一加载就会调到用
System.out.println("调用无参构造器");
} public String getName() {
return name;
} public void setName(String name) {
System.out.println("调用setName方法");
this.name = name;
} public void myInit() {
System.out.println("调用myInit方法");
} public void myDestory(){
System.out.println("调用myDestory方法");
} @Override
public void setBeanFactory(BeanFactory arg0) throws BeansException {
System.out.println("调用setBeanFactory方法"); } @Override
public void setBeanName(String arg0) {
System.out.println("调用setBeanName方法");
}
}
<?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:u="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- 调用set方法赋值后会调用myInit方法 myDestory方法最后调用-->
<bean name="life" class="com.xxx.spring.ioc.bean.Life" init-method="myInit" destroy-method="myDestory">
<property name="name" value="tom"></property>
</bean>
</beans>
@Test
public void life(){//springBean的生命周期
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("com/xxx/spring/chap2/life.xml");
Life life = ac.getBean("life",Life.class);
System.out.println(life);
ac.destroy();
}
调用setName方法
调用setBeanName方法
调用setBeanFactory方法
调用myInit方法
com.briup.spring.ioc.bean.Life@4f0b5b
调用myDestory方法
AfterClass 标注的方法 会最后执行
5.3Bean作用域
5.4Bean的自动装配
this.address = address;
}
<?xml version="1.0" encoding="UTF-8"?>
<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-3.2.xsd">
<bean name="student" class="com.xxx.spring.ioc.bean.Student" autowire="constructor"><!-- byName byType constructor(一定要提供一个单参数的构造器)-->
<property name="name" value="tom"/>
<property name="age" value="20"/>
<!-- <property name="address" ref="address"/> -->
</bean>
<bean name="address" class="com.briup.spring.ioc.bean.Address">
<property name="country" value="中国"></property>
<property name="province" value="江苏"></property>
<property name="city" value="苏州"></property>
</bean>
</beans>
5.3 Aware
<?xml version="1.0" encoding="UTF-8"?>
<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-3.2.xsd">
<bean name="applicationAawareTest" class="com.xxx.spring.aop.bean.AwareTest"></bean>
</beans>
AwareTest.java
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; public class AwareTest implements ApplicationContextAware,BeanNameAware{ @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println(applicationContext.getBean(AwareTest.class));
} @Override
public void setBeanName(String beanName) {
System.out.println(beanName);
} }
@Test
public void AwareTest(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("com/xxx/spring/chap1/aware.xml");
AwareTest awareTest = ac.getBean("applicationAawareTest",AwareTest.class);
System.out.println(awareTest);
}
com.xxx.spring.aop.bean.AwareTest@1d8fe20
com.xxx.spring.aop.bean.AwareTest@1d8fe20
5.4Resource统一文件资源接口
Resources针对文件的统一接口,用于操作本地资源或网络资源,或其他
-UrlResource:URL对应的资源,根据一个URL地址既可以构建
-ClassPathResource:获取类路径下的资源文件
-FileSystemResource:获取文件系统中的资源文件
-ServletContextResource:ServletContext封装资源,用于访问ServletContext环境下的资源
-InputStreamResource:针对输入流封装的资源
-ByteArrayResource:针对字节数组封装的资源
ResourceLoader
-所用的application context 实现了ResourceLoader接口
spring中ResourceLoader定义如下:
public interface ResourceLoader{
Resource getResource(String location);
}
getResource中location的写法有如下几种
prefix前缀 案例 说明
classpath: classpath:com/briup/spring/chap2/life.xml 从classpath中加载
file: file:/data/life.xml用URL从文件系统中加载
http: http://myserver/logoo.png通过URL从网络加载
(none) /spring/chap2/life.xml 这种相对路径的写法依赖于ApplicationContext
spring中的使用
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("file:some/resource/path/myTemplate.txt");
案例:
resources.xml
<?xml version="1.0" encoding="UTF-8"?>
<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-3.2.xsd">
<bean name="resourcetest" class="com.briup.spring.aop.bean.ResourceTest"/>
</beans>
ResourceTest.java
由于spring中所有的applicationcontext实现了ContextLoader接口, 所以我们实现applicationContext即有了ResourceLoader的能力
下边:classpath:在eclipse中会加载src下的config.txt文件
import java.io.IOException; import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource; //所有的ApplicationContext实现了ResourceLoader接口
public class ResourceTest implements ApplicationContextAware{ private ApplicationContext ApplicationContext; @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ApplicationContext = applicationContext;
} public void resource() throws IOException{
//Resource resource = ApplicationContext.getResource("config.txt");//默认为classpath
//Resource resource = ApplicationContext.getResource("classpath:config.txt");
//Resource resource = ApplicationContext.getResource("file:D:\\workspace\\xnxy_spring\\src\\config.txt");
Resource resource = ApplicationContext.getResource("url:http://repo.springsource.org/libs-release-local/org/springframework/spring/3.2.4.RELEASE/spring-framework-3.2.4.RELEASE-dist.zip");
System.out.println(resource.getFilename());//获取文件名
System.out.println(resource.contentLength()); //获取文件长度
System.out.println(resource.getInputStream());//获取输入流
}
}
测试:
@Test
public void ResourceTest(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("com/briup/spring/chap1/resources.xml");
ResourceTest resourceTest = ac.getBean("resourcetest",ResourceTest.class);
try {
resourceTest.resource();
} catch (IOException e) {
e.printStackTrace();
}
}
6.Bean容器的注解实现
Classpath扫描与组件管理
类的自动检测与注册Bean
<context:annotation-config/>
@Component, @Repository, @Service, @Constroller
@Required
@Autowired
@Qualifier
@Resource
6.1classpath扫描与组件管理
@Configuration, @Bean, @Import, @DependsOn
@Component是Spring中的一个通用注解,可以用于任何Bean,相当于注解的超类,如果不知道位于那个层,一般使用该注解
@Repository, @Service, @Controller是更具有针对性的注解
- @Repository,通常用于注解DAO,即持久层的注解
- @Service,通常用于追注解Service类,即服务层
- @Controller通常用于注解Controller,即控制层(MVC)
6.2类的自动检测与注册Bean
<context:component-scan base-package="spring.aop.bean.annotation"></context:component-scan>
我们还可以使用如下标签,context:annotation-config,不过context:component-scan包含context:annotation-config的全部功能,通常使用前者后,不再使用后者,context:component-scan一般用于基于类的注解(包括成员变量或成员方法的注解),但是context:annotation-config只能在完成bean注册后,去处理bean类中的成员变量或成员方法的注解.
<!--默认情况下,spring中自动发现并被注册bean的条件是:
使用@Component, @Repository, @Service, @Constroller其中之一的注解
或者使用基于@Component的自定义注解 可以通过过滤器修改上边的行为,如下边的例子XML配置忽略所有@Repository注解并用“stub”代替
--> <context:component-scan base-package="spring.aop.bean.annotation">
<!-- 通过include-filter包含注解,exclude-filter排除注解 -->
<context:include-filter type="regex" expression=".*Stub.*Repository"/>
<!-- 排除@Repository注解 -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
6.3使用注解管理bean
都会有个name属性用于显示设置BeanName)
//显示设置beanName,相当于在xml配置bean的是id的值
@Service("myMoveLister")
public class simpleLlister{
//..
}
Dao
//设置beanName默认使用类名,首字母小写作为beanName
@Repository
public class MovieFinderImpl implements MovieFinder{
}
6.3.1 作用域scope
作用域的注解Scope
通常情况下自动查找的Spring组件,其Scope是singleton,其Spring2.5提供了Scope的注解 @Scope
@Scope("prototype") //括号中指定Scope的范围,默认
@Repository
public class MovieFinderImpl implements MovieFinder{
}
也可以自定义scope策略,实现ScopeMetadataResolver接口并提供一无参数的构造器
<context:component-scan base-package="spring.aop.bean.MyScopeResolver"></context:component-scan>
6.3.2注解的具体案例使用
//由于不知道其作用于DAO或Service所以使用通用注解,如果知道具体作用在那层,我们一班使用更具体注解方式如@Service,@Repository等
//@Component -->默认使用类名小写作为bean的name
@Scope("prototype") //括号中为Scope的范围,这里设置为原型模式
@Component("beanAnnotation")
public class BeanAnnotation { public void say(String arg){
System.out.println("BeanAnnotation: "+arg);
}
}
测试:
@Test
public void testAnnotation(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("com/xxx/spring/chap4/annotation.xml");
//@Component没有value值的话,默认使用类名首字母小写作为bean的id,指定value以value值为准作为id
BeanAnnotation beanAnnotation1 = ac.getBean("beanAnnotation",BeanAnnotation.class);
BeanAnnotation beanAnnotation2 = ac.getBean("beanAnnotation",BeanAnnotation.class);
System.out.println(beanAnnotation1);
System.out.println(beanAnnotation2);
//结果
//com.xxx.spring.aop.bean.annotation.BeanAnnotation@1598d5f
//com.xxx.spring.aop.bean.annotation.BeanAnnotation@505fd8
}
6.3.3一个不常用的注解@Required
这个注解仅仅标识,受影响的bean属性必须在配置时被填充,通过bean定义或通过自动装配一个明确的属性值
private MoiveFinder movieFinder;
@Required
public void setMovieFinder(MovieFinder movieFinder){
this.movieFinder = movieFinder;
}
//..
}
6.3.4@Autowired
这个注解相当于我们之前在xml文件中配置的autowire="constructor/byName/byType",只不过我们这里使用@Autowired方式注解方式,且默认是通过类型判断,意思就是不使用byName,和construtor。通过@Autowired注解,spring会自动去容器中查找对应的类型,注入到该属性中,且bean类中,使用@Autowired注解其属性,我们可以不用提供getter,setter方法
使用@Autowired
@Autowried对属性进行注解的时候,我们可以省略getter,setter方法,通过对应的bean的类型,对属性值注入
@Autowried对seter方法进行注解的时候,可以注入对应的值
@Autowried对构造器进行注解的时候,可以通过类型找到对应的bean注入
@Autowried可以将 @Autowried为”传统“的setter方法代替 @Required
@Autowried自动注入,会去容器中按照类型查找对应的bean注入
案例:
setter中使用
pulic class simpleMovieLister{ private MoiveFinder movieFinder; @Autowried
public void setMovieFinder(MovieFinder movieFinder){
this.movieFinder = movieFinder;
}
//..
}
属性和构造器中使用
pulic class MovieRreCommender{ 成员变量中
@Autowried
private MovieCatalog movieCatalog; private CustomerPreferenceDao customerPreferenceDao; //构造器中
@Autowried
public MovieRreCommender(CustomerPreferenceDao customerPreferenceDao){
this.CustomerPreferenceDao = CustomerPreferenceDao;
}
}
上边的seter方式,构造器方式,属性方式,效果都是一样的,使用其中任何一种,都可以实现注入。不过由于,@Autowired是通过类型判断是否注入到使用该注解地方,假如容器中出现两个以上的相同类型的bean实例,就会报错,这时我们就必须指定注入那个id名的bean实例,主要有两种方法解决该问题:
@Autowired(requried=false), @Qualifie("beanName)指定@Autowired注入那个bean实例
6.3.5@Autowried(requried=false)
默认情况下,如果因找不到合适的bean将会导致autowiring失败抛出异常,可以通过下边
这种方式避免
pulic class simpleMovieLister{
private MoiveFinder movieFinder;
@Autowried(requried=false)//指明该属性不是必须的,找不到的情况下不会抛出异常
public void setMovieFinder(MovieFinder movieFinder){
this.movieFinder = movieFinder;
}
//..
}
提示:每一类中只能有一个构造器被标记为requried=ture建议将 @Autowired的必要属性时,使用 @Requried注解
6.3.6@Qualifier--配合 @Autowired
注解缩小注解范围(或指定唯一),也可以用于指定单独的构造参数的方法参数
可以适用于注解集合类型的变量
案例:
public class MovieRecommander{
@Autowired
@Qualifier("beanName")
private MovieCatalog movieCatalog; private CustomerPreferenceDao customerPreferenceDao;
//@Qualifier也可以实现参数的注入
public void prepare(@Qualifier("beanName")CustomerPreferenceDao customerPreferenceDao){
this.customerPreferenceDao = customerPreferenceDao;
}
}
上边的案例:假设MovieCatalog在容器中存在多个相同的类型的情况下,可以结合使用 @Qualifier("beanName")
指定一个bean的id注入到该属性中,可以在方法的参数中使用
6.3.7@Autowired注解可以方便的注解那些众所周知的解析依赖性接口
比如说:BeanFacotry,ApplicationContext,Environment,ResourceLoader,ApplicaiontEventPublisher, MessageSource等
pulic class simpleMovieLister{ @Autowired
private AplicationContext context; public simpleMovieLister(){} }
上边的案例使用autowired注解ApplicationContext,这样我们就可以活ApplicatioinContext容器总的bean对象
6.3.8@Autowired将容器中相关类型的bean注入到一个集合或数组中
public interface BeanInterface { }
@Order(1)
@Component
public class BeanImplOne implements BeanInterface { }
@Order(2) //Order排序注解只对list,或数组集合有效括号里边是排序顺序
@Component
public class BeanImplTwo implements BeanInterface { }
调用类:
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; @Component
public class BeanInvoker { @Autowired //该注解会将所有的BeanInterface类型的bean注入到该list中
//如果bean有 @Order注解可以实现排序
private List<BeanInterface> list; //该注解会将所有的BeanInterface类型的bean注入到该map中,key值为bean的名字
//是String类型,map类型无排序可言
@Autowired
private Map<String, BeanInterface> map; public void print(){
if(list != null && 0 != list.size()){
System.out.println("list...");
for(BeanInterface beanInterface:list){
System.out.println(beanInterface.getClass().getName());
}
}
if(map != null && 0 != map.size()){
System.out.println("map...");
Set<Entry<String, BeanInterface>> entrySet = map.entrySet();
for(Entry<String, BeanInterface> entry: entrySet){
System.out.println(entry.getKey()+"--"+entry.getValue().getClass().getName());
}
}
}
}
测试类:
@Test
public void testAutowired2(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("com/xxx/spring/chap4/annotation.xml");
BeanInvoker beanInvoker = (BeanInvoker) ac.getBean("beanInvoker");
beanInvoker.print();
}
结果:
com.xxx.spring.aop.bean.annotation.BeanImplOne
com.xxx.spring.aop.bean.annotation.BeanImplTwo
map...
beanImplOne--com.xxx.spring.aop.bean.annotation.BeanImplOne
beanImplTwo--com.xxx.spring.aop.bean.annotation.BeanImplTwo
6.4@Bean注解的使用
@Configuration //相当于配置文件
public class Appconfig{ @Bean("myservice")//假如bean的name属性没有指定名字的话,注入的是id为方法名的bean,一般我们指定name属性不容易出错
public Myservice myservice(){
return new MyServiceImpl();
}
/*
对比基于XML文件中的配置效果类似
<bean id="myservice" class="com.xxx.service.MyserviceImpl"></bean>
*/
}
@Bean中的其他他几个属性
<bean name="life" class="com.briup.spring.ioc.bean.Life" init-method="myInit" destroy-method="myDestory">
<property name="name" value="tom"></property>
</bean>
我们使@Bean配置也可以实现上边这种效果
public class Foo{
public void init(){ }
} public class Bar{
public void cleanup(){ }
}
@Configuration
public class Appconfig{ @Bean(name="life") //定义bean的name
public Life life(){
return new Life();
} @Bean(initMethod="init") //在初始化Foo的时候,会调用Foo.java中的init方法
public Foo foo(){
return new Foo();
} @Bean(destoryMethod=“cleanup”) //在销毁Bar的时候会调用Bar.java中的cleanup中的方法
public Bar bar(){
return new Bar();
}
}
6.5使用注解模拟连接数据库
jdbc.url=jdbc:oracle:thin:@localhost:1521:XE
jdbc.username=caojx
jdbc.password=caojx
config.xml配置如下
<?xml version="1.0" encoding="UTF-8"?>
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" >
<!-- 加载db.properties文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!--context:component-scan包含context:annotation-config的全部功能,通常使用前者后,不再使用后者
<context:component-scan base-package="com.briup.spring.aop.bean.annotation"></context:component-scan> </beans>
public class MyDriverManager { public MyDriverManager(String url, String userName, String password){
System.out.println("url :"+url);
System.out.println("userName :"+userName);
System.out.println("password :"+password);
} }
@Configuration
@ImportResource("classpath:com/xxx/spring/chap4/config.xml") //指定配置文件的路径
public class MyConnection { @Value("${jdbc.url}") //基本类型的变量使用@Value注解(括号里边是注入的值) ,这是使用${是读取配db.properties中的值}
private String url; @Value("${jdbc.username}") //如果db.properties中写法为username默认取的是当前操作系统用户的名称,可以在db.properties定义username的时候使用jdbc.username
private String userName; @Value("${jdbc.password}")
private String password; @Bean(name="myDriverManager") public MyDriverManager MyDriverManager(){
return new MyDriverManager(url,userName,password);
} }
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("com/xxx/spring/chap4/annotation.xml");
System.out.println(ac.getBean("myDriverManager"));
结果:
url :jdbc:oracle:thin:@localhost:1521:XE
userName :caojx
password :caojx
com.briup.spring.aop.bean.annotation.MyDriverManager@152b54b
同时:@Bean注解也可以配置@Scope使用
@Bean(name="myDriverManager")
@Scope("prototype")
public MyDriverManager MyDriverManager(){
return new MyDriverManager(url,userName,password);
} @Bean(name="myDriverManager")
@Scope("singleton")
public MyDriverManager MyDriverManager(){
return new MyDriverManager(url,userName,password);
}
提示:spring配置数据库连接,或事务管理这一块,将会专门使用一篇来说明。
6.6Spring对JSR的注解支持
JSR常见的注解有如下
@Resource等效于@Autowired与@Inject
@PostConstrct 初始化回掉
@PreDetory 销毁回调用
@Inject 等效于 @Autowired
@Named 与 @Compenet等效
6.6.1@Resource
而@Resource默认按 byName自动注入罢了。
@Resource有两个属性是比较重要的,分是name和type,
Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。
所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。
@Resource装配顺序
1. 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3. 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4. 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;
5. 如果 @Resource用于方法中,默认使用方法名作为beanName,指定名字则使用名字
案例:
DAO
import org.springframework.stereotype.Repository; @Repository
public class JsrDAO { public void save(){
System.out.println("JsrDao invoker");
} }
Service
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.briup.spring.aop.bean.annotation.dao.JsrDAO; @Service
public class JsrService { @Resource
private JsrDAO jsrDAO; @Resource //作用与上边一样,二选一都可以
public void setJsrDAO(JsrDAO jsrDAO){
this.jsrDAO = jsrDAO;
} public void save(){
jsrDAO.save();
} @PostConstruct
public void init(){
System.out.println("jsr Service init");
} @PreDestroy
public void destory(){
System.out.println("jsr Service destory");
} }
提示:
@Resource的处理是由ApplicationContext中的CommonAnnotationBeanPostProecssor发现并处理的
CommonAnnotationBeanPostProecssor不仅支持 @Resource注解,还支持 @PostConstruct初始回调
和 @PreDestory销毁回调,前提是CommonAnnotationBeanPostProecssor是在ApplicationContext中注册的
测试结果:
@Test
public void testJsr(){
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("com/briup/spring/chap4/annotation.xml");
System.out.println(ac.getBean("jsrService"));
ac.destroy();
}
结果:
jsr Service init
com.briup.spring.aop.bean.annotation.service.JsrService@7dc4cb
jsr Service destory
@Resource是一个比比较常用的JSR注解,对于JSR中的其他注解,这里不进行详细的介绍。
spring bean的介绍以及xml和注解的配置方法的更多相关文章
- MyBatis 使用简单的 XML或注解用于配置和原始映射
MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis .My ...
- 【Spring】Spring中的Bean - 5、Bean的装配方式(XML、注解(Annotation)、自动装配)
Bean的装配方式 简单记录-Java EE企业级应用开发教程(Spring+Spring MVC+MyBatis)-Spring中的Bean 文章目录 Bean的装配方式 基于XML的装配 基于注解 ...
- 使用spring框架时,使用xml还是注解
1 xml的优缺点 1.1 优点 解耦合,方便维护.xml不入侵代码,方便代码阅读. 1.2 缺点 开发速度慢. 2 注解的优缺点 2.1 优点 能够加快开发速度,因为它将常用的主体逻辑隐藏在注解中了 ...
- Struts2 注解零配置方法(convention插件使用)
最近接触到一个新的项目,是做一个使用S2SH的电子商务商城的二次开发.之前使用过S2SH,在此之前的项目中,Struts2 使用的是XML配置而这个项目是使用注解.在这个项目中,注解还不需要使用Act ...
- Spring MVC 使用介绍(五)—— 注解式控制器(一):基本介绍
一.hello world 相对于基于Controller接口的方式,基于注解方式的配置步骤如下: HandlerMapping 与HandlerAdapter 分别配置为RequestMapping ...
- Spring事务的介绍,以及基于注解@Transactional的声明式事务
前言 事务是一个非常重要的知识点,前面的文章已经有介绍了关于SpringAOP代理的实现过程:事务管理也是AOP的一个重要的功能. 事务的基本介绍 数据库事务特性: 原子性 一致性 隔离性 持久性 事 ...
- Spring第八篇【XML、注解实现事务控制】
前言 本博文主要讲解Spring的事务控制,如何使用Spring来对程序进行事务控制-. 一般地,我们事务控制都是在service层做的..为什么是在service层而不是在dao层呢??有没有这样的 ...
- Spring MVC 使用介绍(六)—— 注解式控制器(二):请求映射与参数绑定
一.概述 注解式控制器支持: 请求的映射和限定 参数的自动绑定 参数的注解绑定 二.请求的映射和限定 http请求信息包含六部分信息: ①请求方法: ②URL: ③协议及版本: ④请求头信息(包括Co ...
- Spring MVC 使用介绍(七)—— 注解式控制器(三):生产者与消费者模型
一.MIME类型 MIME类型格式:type/subtype(;parameter)? type:主类型,任意的字符串,如text,如果是*号代表所有 subtype:子类型,任意的字符串,如html ...
随机推荐
- cmd 中粘贴复制(转)
1 如右图,右键命令提示符窗口的标题栏,选择属性. 2 选择“编辑选项”里的“快速编辑模式”,并确定之: 3 在弹出的应用选择提示框上选择“保存属性,供以后具有相同标题的窗口使用”: 4 如此你就可以 ...
- Codeforces 163E(ac自动机、树状数组)
要点 显然ac自动机的板子就可以暴力一下答案了 为了优化时间复杂度,考虑套路fail树的dfs序.发现本题需要当前这个尾点加上所有祖先点的个数,考虑使用树状数组差分一下,在父点+1,在子树后-1,每次 ...
- 寒假作业第二组C题题解
这道题题意很简单,主要是练习map的使用.看输入有三个数据,水果名,地名,和出现次数.再看输出,很容易想到map<string,int> string是水果,int是次数,那个地名怎么用m ...
- Java EE学习笔记(八)
动态SQL 1.动态SQL中的元素 1).作用:无需手动拼装SQL,MyBatis已提供的对SQL语句动态组装的功能,使得数据库开发效率大大提高! 2).动态SQL是MyBatis的强大特性之一,My ...
- 物体检测丨从R-CNN到Mask R-CNN
这篇blog是我刚入目标检测方向,导师发给我的文献导读,深入浅出总结了object detection two-stage流派Faster R-CNN的发展史,读起来非常有趣.我一直想翻译这篇博客,在 ...
- Lodop套打
记录一下Lodop套打模板 实现打印功能需电脑已经连接打印机(打印什么类型的东西就连接相应的打印机 (普通大打印机 打印标签 打印发票各种打印机))和已经安装好lodop控件 控件可到官网进行下载 h ...
- Jquery使用ajax参数详解
记录一下 Jquery使用ajax(post.get及参数详解) 1.get: $.ajax({ type: "GET", url: baseUrl + "Showco ...
- 一、Postgresql的基本操作
---------------------------------------------------------------------------------------------------- ...
- IO流----转换流、缓冲流
打开一个文本文件,另存为: Ansi就是系统默认编码(就是gbk) 建一个编码是utf-8的txt文件, 例: import java.io.FileWriter; import java.io.IO ...
- hystrix 给方法加断路器
添加依赖 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>s ...