spring注解的使用,这个例子来源于网上,我也不知道原创是哪个了。。
1.定义接口
package com.isa.demo1.service;
public interface Man {
public String sayHello();
}
2.第一个实现类
package com.isa.demo1.service;
import org.springframework.stereotype.Service;
@Service
public class Chinese implements Man {
@Override
public String sayHello() {
return "i am chinese!";
}
}
第二个实现类
package com.isa.demo1.service;
import org.springframework.stereotype.Service;
@Service
public class American implements Man {
@Override
public String sayHello() {
return "i am american!";
}
}
3.配置文件applicationContext.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" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" default-lazy-init="true"> <context:annotation-config/> <context:component-scan base-package="com.isa.demo1.*"/> </beans>
4.简单测试类
package com.isa.demo1.test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import com.isa.demo1.service.Man;
@Service
public class ManTest {
@Autowired
@Qualifier("american")
private Man man;
public Man getMan() {
return man;
}
public static void main(String[] args){
ApplicationContext ctx = new ClassPathXmlApplicationContext("demo1/applicationContext.xml");
ManTest test = (ManTest)ctx.getBean("manTest");
System.out.println(test.getMan().sayHello());
}
}
5.结果,在此省略了。。
6.说明:spring提供了很多注解来减少配置文件,这样带来的好处显而易见,但是也有人说它增加了代码之间的耦合,其实我觉得只要能提高开发效率,让代码更易阅读才是王道。
这里记录一下自己走的一些弯路,第一个算是基础,关于xml的,需要引入对应版本的xsd,就是xml的格式定义文件,比如“component-scan”这个节点就是spring2.5以后才有的。第二个就是“component-scan”节点的value。第三个,@Service注释表示定义一个bean,自动根据bean的类名实例化一个首写字母为小写的bean,例如Chinese实例化为chinese,American实例化为american,如果需要自己改名字则:@Service("你自己改的bean名")。 刚开始学的时候比较疑惑知道看到这句话。
7.在第一个补一下几个demo的源码吧。所用到的jar包基本上可以在springside的demo中找到。