多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## spring是不是只能实例自己包下创建的类 如果是别人包下的类,spring能不能也给实例化出来.例如C3P0连接池的包. spring不仅可以实例化自己的类,也可以实例化其他包下的类. ## 原生方式 ~~~ ComboPooledDataSource dataSource = new ComboPooledDataSource(); dataSource.setDriverClass("com.mysql.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mysql://192.168.10.10:3306/hibernate"); dataSource.setUser("homestead"); dataSource.setPassword("secret"); Connection connection = dataSource.getConnection(); ~~~ ## 使用IoC ~~~ <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="DriverClass" value="com.mysql.jdbc.Driver"/> <property name="jdbcUrl" value="jdbc:mysql://192.168.10.10:3306/hibernate"/> <property name="user" value="homestead"/> <property name="password" value="secret"/> </bean> ~~~ ~~~ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); ComboPooledDataSource dataSource = (ComboPooledDataSource) context.getBean("dataSource"); System.out.println(dataSource.getConnection()); ~~~ ## 最终版本 spring提供了一个标签可以加载外部的properties文件. 导入context的名称空间和约束. src下的config.properties文件: ~~~ jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://192.168.10.10:3306/hibernate jdbc.username=homestead jdbc.password=secret #jdbc.driver=com.mysql.jdbc.Driver #jdbc.url=jdbc:oracle://localhost:3306/hibernate #jdbc.username=root #jdbc.password=1234 #jdbc.driver=com.mysql.jdbc.Driver #jdbc.url=jdbc:db2://localhost:3306/hibernate #jdbc.username=root #jdbc.password=1234 ~~~ 配置文件: ~~~ <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:property-placeholder location="classpath:config.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="DriverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> </beans> ~~~