随着spring3的发布,终于可以去掉那讨厌的xml了; 具体例子: 下载spring3,目前的版本没有提供spring.jar(all in one) 所以就需要全部引入dist目录下的所有jar,当然,也可以按需引入
spring3还依赖第三方jar,它们是: asm.jar cglib.jar commons-logging.jar 当然少不了数据库驱动jar
准备好以上jar后,spring就可以正常工作了 Jdbc.java[可选] —— 该类主要配置了数据库连接信息,如连接串,用户名,密码 AppConfig.java —— 该类相当于之前的applicationContext.xml文件,只是将Bean的定义放到了Java代码中 Service.java —— 你的业务接口类 Client.java —— 客户端测试调用类
<Jdbc.java> public class Jdbc { public static final String JDBC_URL = "jdbc:mysql://localhost:3306/pmsnew"; public static final String JDBC_USER_NAME = "root"; public static final String JDBC_PWD = "root"; } </Jdbc.java> <AppConfig.java> @Configuration public class AppConfig { @Bean public Service myService() { return new Service(dataSource());//将dataSource注入进Service }
@Bean public DataSource dataSource() { return new DriverManagerDataSource(Jdbc.JDBC_URL, Jdbc.JDBC_USER_NAME, Jdbc.JDBC_PWD); } } </AppConfig.java> <Service.java> public class Service {
private JdbcTemplate jdbcTemplate;
public Service(DataSource dataSource){//接收注入进来的dataSource this.jdbcTemplate = new JdbcTemplate(dataSource); }
public String getStr(){ final String sql = "select * from emp"; System.out.println(jdbcTemplate.queryForList(sql)); return "Hello Spring3"; } } </Service.java> <Client.java> public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);//加载配置类 Service srv = ctx.getBean(Service.class); System.out.println(srv.getStr()); } </Client.java>
配置类的加载方式 实际项目中,配置类不可能是一个,肯定是按照模块进行拆分 加载多个配置累的方法 public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AppConfig1.class, AppConfig2.class); ctx.register(AppConfig3.class); ctx.refresh(); MyService myService = ctx.getBean(MyService.class); myService.doStuff(); }
利用@Import组合多个配置类 <配置类> @Configuration public class ConfigA { public @Bean A a() { return new A(); } } @Configuration @Import(ConfigA.class) public class ConfigB { public @Bean B b() { return new B(); } } </配置类> <调用类> public static void main(String[] args) { ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigB.class);//直接加载ConfigB就可以了 // now both beans A and B will be available... A a = ctx.getBean(A.class); B b = ctx.getBean(B.class); } </调用类>
详细用法请参考spring官方文档 再参考参考spring旗下的JavaConfig项目 |