Spring框架 全注解annotation不使用配置文件(SpringConfiguration.java类代替) 补充 xml配置文件没有提示解决
全注解不使用配置文件
首先还是倒包 在原有的jar包:
需Spring压缩包中的四个核心JAR包
beans 、context、core 和expression
下载地址:
https://pan.baidu.com/s/1qXLHzAW
以及日志jar包
commons-logging 和log4j
下载地址:
https://pan.baidu.com/s/1mimTW5i
再增加一个
spring-aop-5.0.1.RELEASE.jar
增加注解功能的jar包名字是aop有些奇怪(不是annotation ,也不是context)
再增加一个
spring-web-4.2.4.RELEASE.jar
本例用于配置C3P0需要网络功能,还需要增加数据库连接的jar包
mysql-connector-java-5.1.7-bin.jar
本篇所需jar包打包下载地址:
https://pan.baidu.com/s/1UUKcm82DplON50W10TjX6A
然后,写一个类代替applicationContext.xml文件
如下:
package cn.itcast.c_all_annotation; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import; //代替applicationContext.xml配置文件
@Configuration
//相当于<context:component-scan base-package="cn.itcast">
@ComponentScan("cn.itcast")
//將DataSourceConfiguration类中的配置引入(分模块开发)
//相当于<import resource="/cn/itcast/property/property_injection.xml"/>
@Import(DataSourceConfiguration.class)
public class SpringConfiguration { }
分模块开发方法,引入另一配置文件 该文件把src下的.properties文件
package cn.itcast.c_all_annotation; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import com.mchange.v2.c3p0.ComboPooledDataSource; //代替applicationContext.xml配置文件
@Configuration
/*
* <context:property-placeholder location="classpath:db.properties" />
* 读取类路径下的db.properties
* spel语言
*/
@PropertySource("classpath:db.properties")
public class DataSourceConfiguration {
@Value("${jdbc.jdbcUrl}")
private String jdbcUrl;
@Value("${jdbc.driverClass}")
private String driverClass;
@Value("${jdbc.user}")
private String user;
@Value("${jdbc.password}")
private String password; // c3p0连接池交给spring容器
// @Bean 将方法的返回值交给spring容器管理.参数就是BeanName
@Bean(name = "dataSource")
public DataSource getDataSource() throws Exception {
// 1 创建连接池对象
ComboPooledDataSource dataSource = new ComboPooledDataSource();
// 2 设置连接池参数
dataSource.setJdbcUrl(jdbcUrl);
dataSource.setDriverClass(driverClass);
dataSource.setUser(user);
dataSource.setPassword(password); return dataSource;
} @Bean
// 该对象配合@PropertySource("classpath:db.properties")注解,完成properties文件读取
public static PropertySourcesPlaceholderConfigurer getPropertySourcesPlaceholderConfigurer() throws Exception {
return new PropertySourcesPlaceholderConfigurer();
}
}
db.properties 文件内容
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/crm
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
测试类如下:
package cn.itcast.c_all_annotation; import java.sql.SQLException; import javax.sql.DataSource; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.itcast.domain.Car;
import cn.itcast.domain.User; public class Demo {
//JUnit不能静态方法 不能返回值
@Test
public void fun1(){ ApplicationContext ac =
new AnnotationConfigApplicationContext(SpringConfiguration.class); User u = (User) ac.getBean("user");
Car c = (Car) ac.getBean("car"); System.out.println(u);
System.out.println(c);
} @Test
public void fun2() throws SQLException{ ApplicationContext ac =
new AnnotationConfigApplicationContext(SpringConfiguration.class); DataSource ds = (DataSource) ac.getBean("dataSource"); System.out.println(ds.getConnection());
} }
测试结果截图

上面测试还顺带测试了一下注解的User和Car类
代码如下:
package cn.itcast.domain; import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component; //<bean name="user" class="cn.itcast.domain.User" />
@Component("user")
/* //注册service层对象
@Service
@Repository //注册Dao层对象
@Controller //注册Web层对象*/
//<bean scope="singleton|prototype" >
@Scope("prototype")
public class User {
@Value("tom") //为name赋值为tom
private String name;
private Integer age;
@Resource(name="car")
/*
* @Autowired 自动注入 有就注入 默认名car开始
* 注意:如果匹配到多个会抛出异常*/
// @Autowired
/*
* 当自动注入匹配到多个对象时,可以使用@Qualifier 指定具体注入哪一个(不常用)
*/
@Autowired
@Qualifier("car2")
private Car car; public User() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} //将赋值注解放到set方法上,可执行方法中判断逻辑
@Value("18")//为age赋值
public void setAge(Integer age) {
System.out.println("public void setAge(Integer age)!");
this.age = age;
} public Car getCar() {
return car;
} public void setCar(Car car) {
this.car = car;
}
//<bean init-method="init" >
@PostConstruct
public void init() {
System.out.println("构造之后初始化方法!");
}
//<bean destory-method="destory" >
@PreDestroy
public void destory() {
System.out.println("销毁之前销毁方法!");
} @Override
public String toString() {
return "User [name=" + name + ", age=" + age + ", car=" + car + "]";
}
}
Car类
package cn.itcast.domain; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; @Component
public class Car { @Value("哈佛H6")
private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} @Override
public String toString() {
return "Car [name=" + name + "]";
} }
以上实现了全注解的Spring设计,并整合了c3p0,且不需要修改DataSourceConfiguration 类中的内容,直接修改.properties文件即可
全注解方式虽然替换掉了XML配置文件 但操作相对繁琐 不建议使用
如果可以直接在类中修改代码就几行搞定,如果使用xml配置也就几行就可以了,比较一下哪个简便
package cn.itcast.b_datasource; import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mchange.v2.c3p0.ComboPooledDataSource; public class Demo {
@Test
//手动创建C3p0连接池
public void fun1() throws Exception{ //1 创建连接池对象
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//2 设置连接池参数
dataSource.setJdbcUrl("jdbc:mysql:///crm");
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource.setMinPoolSize(1);
System.out.println(dataSource.getConnection());
}
下边是xml方法
@Test
//从Spring容器中获得C3p0连接池
public void fun2() throws Exception{
//1 创建spring容器
ApplicationContext ac =
new ClassPathXmlApplicationContext(
"/cn/itcast/b_datasource/dataSource.xml");
//2 获得连接池
DataSource ds = (DataSource) ac.getBean("dataSource");
//3 测试
System.out.println(ds.getConnection());
}
配置文件配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd "> <!-- 读取properties配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- ${jdbc.jdbcUrl} => 引用db.properties文件中jdbc.jdbcUrl对应的值 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" ></property>
<property name="driverClass" value="${jdbc.driverClass}" ></property>
<property name="user" value="${jdbc.user}" ></property>
<property name="password" value="${jdbc.password}" ></property>
<property name="minPoolSize" value="1" ></property>
</bean> </beans>
读取的.properties文件上面已经给过
xml配置文件没有提示解决
window -->preferences-->搜索 xml catalog -->add-->在key中输入约束网址http://www.springframework.org/schema/beans/spring-beans.xsd
-->在location中点击按钮 file system-->找到spring framework 包-->schema-->beans-->最后的那个版本高的-->key type下拉菜单选schema location
Spring框架 全注解annotation不使用配置文件(SpringConfiguration.java类代替) 补充 xml配置文件没有提示解决的更多相关文章
- java spring mvc 全注解
本人苦逼学生一枚,马上就要毕业,面临找工作,实在是不想离开学校.在老师的教导下学习了spring mvc ,配置文件实在繁琐,因此网上百度学习了spring mvc 全注解方式完成spring的装配工 ...
- 跟着刚哥学习Spring框架--通过注解方式配置Bean(四)
组件扫描:Spring能够从classpath下自动扫描,侦测和实例化具有特定注解的组件. 特定组件包括: 1.@Component:基本注解,识别一个受Spring管理的组件 2.@Resposit ...
- springMVC,spring,mybatis全注解搭建框架--第一步,让框架跑起来
自己从事java开发工作也有一年多了,自己却没有亲手搭建一个完整的框架.于是今天自己动手搭建一个,过程中遇到一些问题,倒腾了大半天终于搞定了. 现在给大家分享一下过程,自己也记录下来,以后学习参考使用 ...
- JAVA总结--Spring框架全解
一.Spring简介 Spring 是个java企业级应用的开源开发框架.Spring主要用来开发Java应用,但是有些扩展是针对构建J2EE平台的web应用.Spring 框架目标是简化Java企业 ...
- 10 Spring框架--基于注解的IOC配置
1.工程环境搭建 2.基于注解的IOC配置 IOC注解的分类 (1)用于创建对象的 他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的@Component: 作用: ...
- 10 Spring框架--基于注解和xml的配置的应用案例
1.项目结构 2.基于xml配置的项目 <1>账户的业务层接口及其实现类 IAccountService.java package lucky.service; import lucky. ...
- Spring框架 IOC注解
Spring框架的IOC之注解方式的快速入门 1. 步骤一:导入注解开发所有需要的jar包 * 引入IOC容器必须的6个jar包 * 多引入一个:Spring ...
- Spring XML配置文件无法自动提示 eclipse中XML配置文件open with打开方式选择 XML Editor:注意它的编辑方式也是有两种的design和source
双击XML配置文件,如果打开方式不正确 则如下图: 都是灰色显示,不会有自动提示,也不会有颜色标注 右击XML配置文件,选择打开方式为XML Editor,则会有颜色标注 如果此时没有自动提示 则要手 ...
- 【XML配置文件读取】使用jdom读取XML配置文件信息
在项目中我们经常需要将配置信息写在配置文件中,而XML配置文件是常用的格式. 下面将介绍如何通过jdom来读取xml配置文件信息. 配置文件信息 <?xml version="1.0& ...
随机推荐
- [Xcode 实际操作]七、文件与数据-(18)使用MarkMan与设计师进行心灵沟通
目录:[Swift]Xcode实际操作 本文将演示MarkMan的使用. 在界面开发过程中,最终的效果和设计稿难免有些出入, 通常是颜色.位置.尺寸方面的偏差,使用MarkMan助你领会设计师的意图. ...
- 部署spark 1.3.1 standalong模式
之前已经写过很多次部署spark 的博客,但是之前部署都是照瓢画葫芦,不得其中的细节,并且以前都是部署spark on yarn 部署环境 scala 2.10.2,jdk 1.6,spark 版本1 ...
- C 语言实例 - 矩阵转换
C 语言实例 - 矩阵转换 C 语言实例 C 语言实例 矩阵转换. 实例 #include <stdio.h> int main() { ][], transpose[][], r, c, ...
- mybatis实现简单的增删查改
接触一个新技术,首先去了解它的一些基本概念,这项技术用在什么方面的.这样学习起来,方向性也会更强一些.我对于mybatis的理解是,它是一个封装了JDBC的java框架.所能实现的功能是对数据库进行增 ...
- asp.net core分块上传文件
写完asp.net多文件上传(http://www.cnblogs.com/bestckk/p/5987383.html)后,感觉这种上传还是有很多缺陷,于是...(省略一万字,不废话).这里我没用传 ...
- 渣渣菜鸡为什么要看 ElasticSearch 源码?
前提 人工智能.大数据快速发展的今天,对于 TB 甚至 PB 级大数据的快速检索已然成为刚需,大型企业早已淹没在系统生成的浩瀚数据流当中.大数据技术业已集中在如何存储和处理这些海量的数据上.Elast ...
- postman中添加cookie信息
日常测试中有部分接口请求需要有登录信息,否则调用报错,那如何在postman中添加用户的cookie呢,主要分2个步骤: 第一步: Charles抓包获取Headers信息,拷贝Headers中的Co ...
- Java方式配置Spring MVC
概述 使用Java方式配置Spring MVC,以及回顾一下Spring MVC的各种用法. Spring MVC简述 关于Spring MVC的介绍网上有很多,这里就不再赘述了,只是要说一下,Spr ...
- [转]Hibernate对象的三种状态
在Hibernate中,对象有三种状态:临 时状态(Transient).持久状态(Persistent)和游离状态(Detached). 处于持久态的对象也称为 PO(PersistenceObje ...
- [转]在C#中使用托管资源和非托管资源的区别,以及怎样手动释放非托管资源:
托管资源指的是.NET可以自动进行回收的资源,主要是指托管堆上分配的内存资源.托管资源的回收工作是不需要人工干预的,有.NET运行库在合适调用垃圾回收器进行回收. 非托管资源指的是.NET不知道如何回 ...