Spring中常用注解的使用解释
标签: Spring中常用注解的使用解释 JavaScript博客 51CTO博客
2023-05-19 18:24:20 180浏览
Spring中常用注解的使用解释,@PathVariable//接收请求路径中占位符的值@ConfigurationProperties是springboot提供读取配置文件的一个注解,通过与其他注解配合使用,能够实现Bean的按需配置。该注解有一个prefix属性,通过指定的前缀,绑定配置文件中的配置,该注解可以放在类上,也可以放在方法上@mapper的作用是可以给mapper接口自动生成一个实现类,让spring对ma
@PathVariable //接收请求路径中占位符的值
@ConfigurationProperties是springboot提供读取配置文件的一个注解,通过与其他注解配合使用,能够实现Bean的按需配置。
该注解有一个prefix属性,通过指定的前缀,绑定配置文件中的配置,该注解可以放在类上,也可以放在方法上
@mapper的作用是可以给mapper接口自动生成一个实现类,让spring对mapper接口的bean进行管理,并且可以省略去写复杂的xml文件,也就是被spring容器识别到,产生自动代理的对象
会根据属性名自动匹配



比如在xml中配置数据源可以用注解开发来替代…
<!--配置数据源-->
<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>
<!--配置组件扫描-->
<context:component-scan base-package="com.luozhigang"/>
<!--加载外部的properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
替代方法,使用Java类进行注解开发
package com.luozhigang.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
/**
* @author Luo Zhigang
* @date 2022/1/25 11:19
*/
// 指明该类是spring的核心配置类
@Configuration
@ComponentScan("com.luozhigang")
@PropertySource("classpath:jdbc.properties")
public class SpringCofiguration {
// 将当前方法的返回值以指定名称存储到spring容器中
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean("dataSource")
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
好博客就要一起分享哦!分享海报
此处可发布评论
评论(0)展开评论
暂无评论,快来写一下吧
展开评论
