Spring 注解相关知识

0: 注解扫描

让Spring 扫描指定的包,完整注解扫描
base-package 的值为扫描位置的值,会扫描此包下儿子孙子等所有的文件

   <!--    配置组件扫面 扫描注解实现注解-->
   <!-- 配置一个基本包 Spring 会自动扫面他包含的所有信息  这里是扫面com 包里所有的信息-->
   <context:component-scan base-package="com"></context:component-scan>

1: @Component:

通用的注解,表示该类为Spring的组件 设置id 被spring管理 可以带参数()括号里写 id值,也可以不带参数,没有括号,id值为类名首字母小写剩下的不变

使用方法:

没有括号,id值为类名首字母小写剩下的不变
有括号,括号里为id值

@Component("pig_dao")
public class PigDaoimpl implements Pig {
    public void eat() {
        System.out.println("猪正在吃东西 吃的很香");
    }
}
等价于:
<bean id="pig_dao" class="com.fullstuck.dao.impl.PigDaoimpl"></bean>

2.@Autowired

这个注解就是spring可以自动帮你把bean里面引用的对象的setter/getter方法省略,它会自动帮你set/get。
如果@Autowired后面没有写@Qualifier 则是类型注入,否则就是名称注入。类型注入时如果有一个类型有多个Bean,Spring就会不知道向哪一个注入

使用方法:

把下面的属性进行set get

    @Autowired
    @Qualifier("pig_dao")
    private PigDaoimpl pig;
等价于:
//实现set方法
    public void setPig(PigDaoimpl pig) {
        this.pig = pig;
    }

3.@Qualifier

两个实现类实现统一接口,那么可以使用Qualifier 选取你想用的接口(后面必须有一个私有属性值),注入引用类型

使用方法:

把下面的属性进行注入

    @Autowired
    @Qualifier("pig_dao")
    private PigDaoimpl pig;

等价于:
<property name="pig" ref="pig_dao"></property>

4.@Service

当前类为业务层,可以被Spring管理,后期就可以处理事物
Service 层上的@Component 标签,提高可读性

使用方法:

没有括号,id值为类名首字母小写剩下的不变
有括号,括号里为id值

@Service("pid_service")
public class PigServiceimpl implements PigService {
等价于:
<bean id="pid_service" class="com.fullstuck.service.impl.PigServiceimpl">

5.@Controller

标识将该类定义为SpringMVC的Controller控制器
web 层上的@Component 标签,提高可读性

使用方法:

没有括号,id值为类名首字母小写剩下的不变
有括号,括号里为id值

@Controller
public class AdController {
等价于:
<bean id="adController" class="com.fullstuck.controller.AdController">

6.@Repository

表示dao 设置自己的id
DAO层上的@Component 标签,提高可读性

使用方法:

没有括号,id值为类名首字母小写剩下的不变
有括号,括号里为id值

@Repository("pig_dao")
public class PigDaoimpl implements Pig {
等价于:
<bean id="pig_dao" class="com.fullstuck.dao.impl.PigDaoimpl"></bean>

7.@Resource

依赖注入,等同于 @Autowired+@Qualifier,注入引用类型

使用方法:

name 的值为要注入bean的id值

@Resource(name = "pig_dao")
    private PigDaoimpl pig;
等价于:
<bean id="pig_dao" class="com.fullstuck.dao.impl.PigDaoimpl"></bean>

    @Autowired
    @Qualifier("pig_dao")
    private PigDaoimpl pig;

8.@Value

依赖注入,注入普通类型

使用方法:

括号里写注入的值

@Value("猪叫猪八戒")
    private String pigName;
等价于:
<property name="pigName" value="猪八戒"></property> 
注入,读取 .properties文件的值

首先引入 .properties

<!--   引入db.properties-->
    <context:property-placeholder location="classpath:db.properties"/>

然后

@Value("${jdbc.driver}")
 private String driver;

等价于

<property name="pigname" value="${jdbc.driver}"></property> 

9.@Scope

设置bean 的scope 属性

scope 指对象作用范围,有以下取值:
singleton 默认值,单例
prototype 多例
request WEB中,Spring创建一个Bean对象,将对象存入request中
session WEB中,Spring创建一个Bean对象,将对象存入session中
global session WEB中,应用在Portlet环境中,如果没有Portlet环境那么global session 相当于session

当scope 取值为singleton 时,在加载Spring核心文件时对象就被创建
prototype时,在每一次getBean方法执行时创建对象

使用方法:
@Service("pid_service")
@Scope("singleton")
public class PigServiceimpl implements PigService {
等价于:
<bean id="pig_dao" class="com.fullstuck.dao.impl.PigDaoimpl" scope="singleton"></bean>

10.@PostConstruct

设置bean刚创建时执行的方法 等同 init-method

使用方法:
 //初始化前执行
    @PostConstruct
    public void begin(){
        System.out.println("pig 初始化");
    }
等价于:
<bean id="pig_dao" class="com.fullstuck.dao.impl.PigDaoimpl" init-method="begin"></bean>

11.@PreDestroy

设置bean销毁时执行的方法 等同 destroy-method

使用方法:
 //初始化前执行
    @PreDestroy
    public void begin(){
        System.out.println("pig 初始化");
    }
等价于:
<bean id="pig_dao" class="com.fullstuck.dao.impl.PigDaoimpl" destory-method="begin"></bean>

Spring 新注解部分

为了代替 applicationConfig.xml配置文件,在class里配置,所使用的注解部分

1.@Configuration

将这个类设置为Spring 配置类
使用方法:

//设置为spring配置文件 applicationConfig.xml
@Configuration
public class SpringConfiguration {

可以有多个class设置此属性,只要最后都导入到总文件下就行

2.@PropertySource

导入 .properties文件,前提是这个类是被@Configuration修饰的类
使用方法:

@PropertySource("classpath:db.properties")  //括号里写 classpath:具体文件名字
public class C3P0Configuration {

等同于:

<!--   引入db.properties-->
<context:property-placeholder location="classpath:db.properties"/>

3.@ComponentScan

组件扫描,括号填入扫描的包名,前提是这个类是被@Configuration修饰的类
使用方法:

@ComponentScan("com")
public class SpringConfiguration {

等价于:

<context:component-scan base-package="com"></context:component-scan> 

4. @Import

导入相关class,导入的都是Spring副配置类,一般这个写在Spring核心主类里
使用方法:

@Import({A.class,B.class})//这里是一个数组,可以写多个class目标
public class SpringConfiguration {

等价于:

<import resource="applicationContext-A.xml"></import>
<import resource="applicationContext-B.xml"></import>

5. @Bean

会将当前方法返回值以指定名称存储到Spring容器中,括号里设置id值 ,一般写在自定义的方法上面,方法一般是代替xml中的一些功能配置,例如代替C3P0数据库连接池的使用
使用方法:

 @Bean("dateSource")    //Spring 会将当前方法返回值以指定名称存储到Spring容器中   设置id值
    public DataSource getDataSource() throws Exception{
        //导入c3p0
        //建立对象
        ComboPooledDataSource source = new ComboPooledDataSource();

        //配置数据库信息
        source.setDriverClass(driver);
        source.setJdbcUrl(url);
        source.setUser(name);
        source.setPassword(password);

        //连接数据库 后续操作和普通JDBC一样了
        Connection connection = source.getConnection();
        //打印连接信息,说明连接上了
        System.out.println(connection);

        connection.close();

        return source;
    }

等价于:

 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.name}"></property>
        <property name="password" value="${jdbc.password}"></property>
 </bean>

附带C3P0 xml 配置:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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">
<!--   引入db.properties-->
    <context:property-placeholder location="classpath:db.properties"/>

<!--        这里的class 是找到 new ComboPooledDataSource() 右键选择 Path refenerce 得到的-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.name}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <!-- 每60秒检查所有连接池中的空闲连接。Default: 0 -->
        <property name="idleConnectionTestPeriod" value="60" />
        <!-- 初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
        <property name="initialPoolSize" value="5" />
        <!-- 最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
        <property name="maxIdleTime" value="60" />
        <!-- 连接池中保留的最大连接数。Default: 15 -->
        <property name="maxPoolSize" value="10" />
        <!-- 连接池中保留的最小连接数。 -->
        <property name="minPoolSize" value="5" />
        <!-- JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
        属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
        如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
        <property name="maxStatements" value="100" />
        <!-- maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0  -->
        <property name="maxStatementsPerConnection" value="3" />
        <!-- 定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个显著提高测试速度。注意:
        测试的表必须在初始数据源的时候就存在。Default: null -->
        <property name="preferredTestQuery" value="select 1" />
        <!-- 定义在从数据库获取新连接失败后重复尝试的次数。Default: 30-->
        <property name="acquireRetryAttempts" value="3" />
        <!-- 两次连接中间隔时间,单位毫秒。Default: 1000 -->
        <property name="acquireRetryDelay" value="1000" />
        <!-- 当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出
        SQLException,如设为0则无限期等待。单位毫秒。Default: 0 -->
        <property name="checkoutTimeout" value="30000" />

    </bean>


</beans>

使用注解注意事项:

如果通过注解@Autowired配置了一个注入属性。
例如:

@Autowired
private String name;

这里想再注入具体的值只能通过注解注入,如果想在.xml里注入,还需要写这个变量的的 set 方法。不然会报错。

测试注解:(使用注解代替普通spring 实现)

1.@RunWith

作用:
引入juint 测试Spring 部分

//导入 junit测试
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJuintTest {

2.@ContextConfiguration

作用: 导入Spring 核心配置
参数:classes 类作为核心配置
classpath xml作为核心配置

//导入核心配置文件 导入.xml
@ContextConfiguration("classpath:applicationContext.xml")
//导入class 配置
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJuintTest {

测试具体实现:

通过普通Java class实现 Spring Bean: (配置文件 .xml)

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
PigService pig_service = (PigService)context.getBean("pid_service");
pig_service.dopig_eat();

通过普通Java class实现注解 Spring Bean: (注解配置)

ApplicationContextcontext=newAnnotationConfigApplicationContext(SpringConfiguration.class); //括号里写入 类.class
PigService pid_service = (PigService) context.getBean("pid_service");
pid_service.dopig_eat();

通过注解实现测试 Spring Bean (配置文件 .xml)

首先在pom导入相关配置

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!-- Java 测试类  可以使用@Test注解进行测试     -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

再进行测试

//导入 junit测试
@RunWith(SpringJUnit4ClassRunner.class)
//导入核心配置文件 导入.xml
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJuintTest {

   //导入要测试的实现类
   @Autowired
   private PigServiceimpl pigServiceimpl;

   @Autowired
   private DataSource dataSource;

   //测试
   @Test
   public void test() throws SQLException {
       pigServiceimpl.dopig_eat();
       System.out.println(dataSource.getConnection());
   }
}

通过注解实现测试Spring Bean (注解配置) 全注解开发

首先在pom导入相关配置

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!-- Java 测试类  可以使用@Test注解进行测试     -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

再进行测试


//导入 junit测试
@RunWith(SpringJUnit4ClassRunner.class)
//导入class 配置
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJuintTest {

    //导入要测试的实现类
    @Autowired
    private PigServiceimpl pigServiceimpl;

    @Autowired
    private DataSource dataSource;

    //测试
    @Test
    public void test() throws SQLException {
        pigServiceimpl.dopig_eat();
        System.out.println(dataSource.getConnection());
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容