1.Spring中对配置文件的处理(链接数据库)
连接数据库时,需要maven中pom文件中导入包(8.0.26)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
配置文件(druid.properties):
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名字
name=root
password=自己的密码
需要在Spring中xml文件的头部中导入
xmlns:context="http://www.springframework.org/schema/context"
bean中导入
<context:property-placeholder location="classpath:druid.properties">
</context:property-placeholder>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driverClassName}"></property>
<property name="password" value="${password}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${name}"></property>
</bean>
test类:
@org.junit.Test
public void Test03(){
ApplicationContext context=new ClassPathXmlApplicationContext("Beans01.xml");
DataSource dataSource=context.getBean("dataSource",DruidDataSource.class);
Connection connection=null;
try {
connection=dataSource.getConnection();
System.out.println(connection);
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(connection!=null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
运行结果:
获得连接对象,成功;
2.IOC的注解
什么是注解:
(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值)
(2)使用注解:注解作用在类上面,方法上面,属性上面
(3)使用注解的目的:简化xml配置
在classpath中扫面组件:组件扫描(component scanning);Spring能够从classpath下自动扫描、侦测和实例化具有特定注解的组件
@Componet:基本注解,标识了一个受Spring管理的组件
@Respository:标识持久层组件
@Service:标识服务层(业务层)组件
@Controller:标识表现组件
注解的默认获得的name中,使用非限定类名,第一个字母小写,也可以在注解中通过value属性值标识组件的名称
使用前,需要声明基准包:
<contest:component-scan base-package="com.openlab"></contest:component-scan>
注解就可以省略bean文件的很多重复代码,及施行了解耦
对于基准包下的注释,可以设置忽略某些注解
<context:component-scan base-package="包名">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:component-scan>
只包含某些注解:
<context:component-scan base-package="包名" use-default-filters="false">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:component-scan>
注入
属性的注入;
@Autowired(类型注入):类中属性包含接口时,且该接口只有一个实现类,则可以使用。如果该接口被多个类实现,则会出现异常。
@Qualifier(名字name):如果一个接口有多个实现类,此时无法确定要注入那个实例,就要和@Autowired一起使用,来确定某一个使用哪一个实例进行注入
@Resource:直接根据类型注入,同@Autowired javax包下的,更推荐使用@Autowired+@Qualifier(名字name)
3. 无配置注解
首先需要创建一个类,在该类中,我们需要
(1)标识此类是一个配置@Configuration
(2)告诉需要扫描的信息:@ComponentScan({需要扫描的包});
test测试
ApplicationContext context=new AnnotationConfigApplicationContext(无配置类名.class)
扫描类类名 名字=context.getBean(包中可扫描类的类名.class);
名字.方法名;