欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springIoc及注解的使用實例詳解

 更新時間:2024年02月04日 10:54:44   作者:screamn  
注解(Annotation)是一種在 Java 程序中以元數(shù)據(jù)的形式對代碼進行標記和說明的機制,它可以被添加到類、方法、字段、參數(shù)等程序元素上,用于提供額外的信息和指示,本文給大家介紹springIoc及注解的使用,感興趣的朋友一起看看吧

注解

注解的定義

注解(Annotation)是一種在 Java 程序中以元數(shù)據(jù)的形式對代碼進行標記和說明的機制。它可以被添加到類、方法、字段、參數(shù)等程序元素上,用于提供額外的信息和指示。
也就是說注解是一種標記

注解怎么生效呢?

通過掃描的方式生效,spring容器進行指定包下的文件掃描,然后根據(jù)注解進行后續(xù)操作

注解的類型

  • 內(nèi)置注解(Built-in Annotations):Java語言提供了一些內(nèi)置的注解,用于標記和處理特定的場景和行為。例如:
    • @Override:用于標記方法覆蓋父類方法。
    • @Deprecated:用于標記已過時的方法、類或字段。
    • @SuppressWarnings:用于抑制編譯器警告信息。
  • 元注解(Meta-Annotations):元注解是用于定義和處理注解本身的注解。它們可以用于 自定義注解,指定注解的行為、作用范圍等。常見的元注解包括:
    • @Target:指定注解可應用的目標元素類型(類、方法、字段等)。
    • @Retention:指定注解的保留策略(源代碼、編譯時、運行時)。
    • @Documented:指定注解是否包含在API文檔中。
  • 自定義注解(Custom Annotations):
    • 開發(fā)者可以根據(jù)需要自定義自己的注解,以實現(xiàn)特定的功能和邏輯。自定義注解需要使用元注解來進行配置,并通過反射機制來獲取注解信息。自定義注解可以應用于類、方法、字段等代碼元素,并可以根據(jù)注解信息做出相應的處理。

簡單來說內(nèi)置注解就是 Java語言提供的一些注解,不需要導依賴和導包使用。元注解也就是注解的注解 專門用來標注注解,自定義注解 ,開法者根據(jù)需要自定義自己的注解,也就是自己做的一些規(guī)定,通常需要導包進行使用。

配置包掃描

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

排除包下的一些信息

<context:exclude-filter type="annotion" expression="類的全限定符"/>

指定包含內(nèi)容

<context:include-filter type="annotion" expression="類的全限定符"/>

type="annotation" 表示使用注解作為過濾器的類型,它會匹配帶有特定注解的類進行組件掃描。

bean的作用域和周期方法注解

定義

作用域指的是在Spring容器中管理的Bean對象的生命周期范圍和可見性。不同的作用域決定了在容器中創(chuàng)建的Bean實例的行為方式。
可以使用注解的形式進行規(guī)定

在Spring框架中,常見的Bean作用域(scope)包括:

  • Singleton(單例):
  • 在整個應用程序中只存在一個Bean實例,由Spring容器管理。每次請求該Bean時,都會返回同一個實例。
  • Prototype(原型):每次請求該Bean時,容器都會創(chuàng)建一個新的Bean實例,并返回該實例。
  • Request(請求):每個HTTP請求都會創(chuàng)建一個新的Bean實例,該實例僅在當前請求中有效。
  • Session(會話):每個用戶會話都會創(chuàng)建一個新的Bean實例,該實例在整個會話期間有效。
  • GlobalSession(全局會話):僅適用于Portlet環(huán)境,表示全局會話作用域。

常用的生命周期方法注解包括:

周期的定義

周期(Lifecycle)指的是對象的創(chuàng)建、初始化、使用和銷毀過程中的各個階段。在Spring框架中,可以通過聲明周期方法注解來定義在Bean的生命周期中執(zhí)行的特定方法。

  • @PostConstruct:在Bean的初始化階段,即依賴注入完成后調(diào)用的方法上添加該注解。該方法會在構(gòu)造函數(shù)執(zhí)行之后、任何自動裝配發(fā)生之前被調(diào)用。
  • @PreDestroy:在Bean銷毀之前調(diào)用的方法上添加該注解。該方法會在Bean被容器銷毀之前被調(diào)用。
  • 這兩個就類似于前面說到的bean中的init-method 和destroy-method方法

這兩個就類似于前面說到的bean中的init-method 和destroy-method方法

注解Autowired的使用

它是spring框架的注解,用于自動裝配bean,使用Autowired注解可以簡化依賴注入。當創(chuàng)建一個Bean時,會自動檢測該Bean所需要的依賴,將其注入到Bean中

1.構(gòu)造方法注入:

在構(gòu)造方法上使用 @Autowired的話,spring會嘗試通過匹配類型或名稱來自動注入構(gòu)造方法所需的依賴項

public class MyBean {
    private DependencyBean dependency;
    @Autowired
    public MyBean(DependencyBean dependency) {
        this.dependency = dependency;
    }
}

在上述示例中,MyBean 類的構(gòu)造方法使用了 @Autowired 注解,告訴 Spring 自動注入 DependencyBean 對象。 自動注入也就是說會創(chuàng)建這個實例

2.成員變量注入:在成員變量上使用 @Autowired 注解,Spring 將會自動注入與該成員變量類型匹配的 Bean 對象。

public class MyBean {
    @Autowired
    private DependencyBean dependency;
}

3.Setter 方法注入:
在 Setter 方法上使用 @Autowired 注解,Spring 將會自動注入與該 Setter 方法參數(shù)類型匹配的 Bean 對象。

public class MyBean {
    private DependencyBean dependency;
    @Autowired
    public void setDependency(DependencyBean dependency) {
        this.dependency = dependency;
    }
}

4.方法注入:在普通方法上使用 @Autowired 注解,Spring 將會自動注入與方法參數(shù)類型匹配的 Bean 對象。

public class MyBean {
    private DependencyBean dependency;
    @Autowired
    public void injectDependency(DependencyBean dependency) {
        this.dependency = dependency;
    }
}

在上述示例中,MyBean 類的 injectDependency() 方法使用了 @Autowired 注解,告訴 Spring 自動注入與 DependencyBean 類型匹配的 Bean 對象。

舉例幫助理解

我們來學習一下上面這部分內(nèi)容的實際用處,以及為什么這樣做

1.構(gòu)造方法注入:
我們此時面臨一個場景,我想要在一個類中使用另一個類的實例,比如說在動物類中,使用鳥類的飛行方法,那么我可以在動物類中創(chuàng)建一個鳥類的引用,通過Autowired注解注入,以達到在此類中實現(xiàn)鳥類的飛行方法。
如:我定義一個注入的類 三個私有化屬性 一個重寫的toString方法

@Component
public class DependencyBean {
    private String name;
    private Integer age;
    private String address;
    @Override
    public String toString() {
        return "DependencyBean{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

使用Autowired注解進行注入

@Component
public class MyBean {
    private DependencyBean dependency;
    @Autowired //TODO 這個用法是什么呢?
    public MyBean(DependencyBean dependency) {
        this.dependency = dependency;
    }
    public String sing(){
        dependency.setAddress("地球");
        dependency.setAge(50);
        dependency.setName("張三");
        return dependency.toString();
    }
}

注入之后進行使用

 class Test{
     public static void main(String[] args) {
         ApplicationContext applicationContext =
                 new ClassPathXmlApplicationContext("spring-ioc.xml");
         MyBean bean = applicationContext.getBean(MyBean.class);
         System.out.println(bean);
         System.out.println(bean.sing());
     }
}

結(jié)果:我可以不用創(chuàng)建這個注入的類的對象,使用Autowired會自動幫助我創(chuàng)建

在這里插入圖片描述

2. 成員變量的注入:其余不改,僅更改MyBean內(nèi)容

@Component
public class MyBean {
    @Autowired
    private DependencyBean dependency;
    public String sing(){
        dependency.setAddress("地球");
        dependency.setAge(50);
        dependency.setName("張三");
        return dependency.toString();
    }
}

我們執(zhí)行之后得到的結(jié)果,可以發(fā)現(xiàn)注入的話會自動創(chuàng)建一系列內(nèi)容。相當于得到了實例

3.setter方法的注入

@Component
public class MyBean {
    private DependencyBean dependency;
    @Autowired
    public void setDependency(DependencyBean dependency) {
        this.dependency = dependency;
    }
    public String sing(){
        dependency.setAddress("地球");
        dependency.setAge(50);
        dependency.setName("張三");
        return dependency.toString();
    }
}

效果一樣

在這里插入圖片描述

4.在普通方法上使用

@Component
public class MyBean {
    private DependencyBean dependency;
    @Autowired
    public void injectDependency(DependencyBean dependency) {
        this.dependency = dependency;
    }
    public String sing() {
        dependency.setAddress("地球");
        dependency.setAge(50);
        dependency.setName("張三");
        return dependency.toString();
    }
}

結(jié)果仍一樣

在這里插入圖片描述

我們需要明白Autowired會根據(jù)你規(guī)定或者是表明的內(nèi)容進行注入,從而得到對應的bean對象或者是bean實例。這樣做的話簡化了操作,讓我們實現(xiàn)起來更加的方便。

使用注解實現(xiàn)ioc容器管理

dao層,持久化儲存

package com.dao;
import com.pojo.Student;
import java.util.List;
public interface StudentDao {
    List<Student> queryAll();
}

實現(xiàn)

package com.dao;
import com.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class StudentDaoImpl implements StudentDao{
//    這個位置不可以直接使用注解 需要使用的時 bean的依賴注入
   @Autowired
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    @Override
    public List<Student> queryAll() {
        String sql = "select * from students ";
        List<Student> students = jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Student.class));
        return students;
    }
}

這里我們主要明確,由于JdbcTemplate這個內(nèi)容并不是我們創(chuàng)建的,這是根據(jù)需求導入的jar包,我們并不清楚它的標注是什么,這里仍然需要配置bean,先創(chuàng)建druid 進行配置后,注入依賴到JdbcTemplate中

<?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 https://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com"/>
    <context:property-placeholder location="classpath:jdbcTemplate.properties"/>
    <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="${atguigu.url}"></property>
        <property name="password" value="${atguigu.password}"></property>
        <property name="driverClassName" value="${atguigu.driver}"></property>
        <property name="username" value="${atguigu.username}"></property>
    </bean>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="druidDataSource"/>
    </bean>
</beans>

這樣的話,我們先配置號bean對象,當spring掃描的時候,掃描到Autowired的時候,會自動裝配。只要保證bean的填寫正確,后續(xù)的實例spring會幫助進行

Service層

接口

package com.service;
import com.pojo.Student;
import java.util.List;
public interface StudentService {
    List<Student> queryAll();
}

實現(xiàn)類

package com.service.impl;
import com.dao.StudentDaoImpl;
import com.pojo.Student;
import com.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentsServiceImpl implements StudentService {
    @Autowired
    private StudentDaoImpl studentDao;
    @Override
    public List<Student> queryAll() {
        List<Student> students=  studentDao.queryAll();
        System.out.println("service層的內(nèi)容"+students);
        return students;
    }
}

constroller層內(nèi)容

package com.Constroller;
import com.pojo.Student;
import com.service.impl.StudentsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.util.List;
@Controller
public class StudentsConstroller {
    @Autowired
    private StudentsServiceImpl studentsService;
    public List<Student> findAll(){
        List<Student> student = studentsService.queryAll();
        return  student;
    }
}

代碼書寫完畢之后,我們需要配置掃描,否則,spring的注解就沒有任何效果了。先掃描才可以創(chuàng)建,不掃描的話出現(xiàn)這個錯誤

在這里插入圖片描述

    <context:component-scan base-package="加注解的包名"/>

測試

public class TestIoc {
    @Test
    void testIoc(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-ioc.xml");
        StudentsConstroller bean = applicationContext.getBean(StudentsConstroller.class);
        List<Student> studentList =  bean.findAll();
        System.out.println(studentList);
    }
}

仍然是老套路,先創(chuàng)建根據(jù)配置文件創(chuàng)建ioc容器,創(chuàng)建完成之后,掃描注解進行bean對象的實例,然后執(zhí)行對應的內(nèi)容。

怎么執(zhí)行呢?

通過Autowired進行關(guān)聯(lián),我們可以將依賴看成不同的模塊,A模塊調(diào)用B怎么調(diào)用?,那就是創(chuàng)建B模塊的實例,在A中進行使用,而在這個位置,我們是通過注解的形式進行注入,相當于注解的效果是實現(xiàn)B模塊的實例

在這里插入圖片描述

使用ioc容器獲取控制層對象,使用控制層的對象執(zhí)行后續(xù)的內(nèi)容。

前面我們提到的bean對象的配置,哪里使用的注入是通過指定property的ref進行關(guān)聯(lián)的

在這里插入圖片描述

完全注解的方式進行

我們上述中,配置druid和jdbcTemplate依舊是使用的bean文件配置,現(xiàn)在我們使用注解的形式來替代這個配置。當然使用這個仍然需要用注解來實現(xiàn)

package com.ssm;
import com.alibaba.druid.pool.DruidDataSource;
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 org.springframework.jdbc.core.JdbcTemplate;
@Configuration
@ComponentScan(basePackages = "com.ssm")
@PropertySource("classpath:jdbcTemplate.properties")
public class JavaConfiguration {
    @Value(value = "${atguigu.username}")
    String name;
    @Value(value = "${atguigu.url}")
    String url;
    @Value(value = "${atguigu.password}")
    String password;
    @Value(value = "${atguigu.driver}")
    String driver;
    @Bean
    public DruidDataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUsername(name);
        druidDataSource.setUrl(url);
        druidDataSource.setPassword(password);
        druidDataSource.setDriverClassName(driver);
        return druidDataSource;
    }
    @Bean
    public JdbcTemplate jdbcTemplate(DruidDataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }
}

配置類的實現(xiàn)需要用到的注解有:

  • @Configuration:該注解用于標記一個類,表示這是一個配置類。在 Spring 中,配置類可以替代傳統(tǒng)的 XML 配置文件,用 Java 代碼來配置應用程序的組件。配置類中通常包含了一些 @Bean 注解,用于聲明需要被 Spring 容器管理的 bean。
  • @ComponentScan:該注解用于指定掃描的包路徑,使得 Spring 容器可以自動掃描包下的組件,并將其自動注冊為 bean。如果沒有指定掃描的包路徑,Spring 將掃描該注解所在類的同級包及其子包下的所有組件。
  • @PropertySource:該注解用于指定要加載的屬性文件,其中包含了一些配置參數(shù)。在 Spring 中,我們經(jīng)常需要將配置參數(shù)從屬性文件中讀取,然后注入到組件中,以便我們可以方便地管理和修改它們。使用該注解后,我們就可以通過 @Value 注解或 Environment 對象來獲取屬性值了。
  • @Bean:該注解通常用于方法級別上,用于告訴 Spring 容器,通過該方法返回的對象將被注冊為一個 bean。方法名通常就是 bean 的 id。使用該注解后,Spring 將調(diào)用該方法并將返回的對象添加到容器中。在有些情況下,我們可以在使用 @Bean 注解時指定 bean 的名稱,例如:@Bean(name = “myBean”)。

到此這篇關(guān)于springIoc以及注解的使用的文章就介紹到這了,更多相關(guān)springIoc注解使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Netty + ZooKeeper 實現(xiàn)簡單的服務注冊與發(fā)現(xiàn)

    Netty + ZooKeeper 實現(xiàn)簡單的服務注冊與發(fā)現(xiàn)

    服務注冊和發(fā)現(xiàn)一直是分布式的核心組件。本文介紹了借助 ZooKeeper 做注冊中心,如何實現(xiàn)一個簡單的服務注冊和發(fā)現(xiàn)。,需要的朋友可以參考下
    2019-06-06
  • Java8中利用stream對map集合進行過濾的方法

    Java8中利用stream對map集合進行過濾的方法

    這篇文章主要給大家介紹了關(guān)于Java8中利用stream對map集合進行過濾的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2018-07-07
  • java序列化與反序列化操作實例分析

    java序列化與反序列化操作實例分析

    這篇文章主要介紹了java序列化與反序列化操作,結(jié)合實例形式分析了java序列化與反序列化的概念與具體實現(xiàn)技巧,需要的朋友可以參考下
    2016-10-10
  • Java基于動態(tài)規(guī)劃法實現(xiàn)求最長公共子序列及最長公共子字符串示例

    Java基于動態(tài)規(guī)劃法實現(xiàn)求最長公共子序列及最長公共子字符串示例

    這篇文章主要介紹了Java基于動態(tài)規(guī)劃法實現(xiàn)求最長公共子序列及最長公共子字符串,簡單描述了動態(tài)規(guī)劃法的概念、原理,并結(jié)合實例形式分析了Java使用動態(tài)規(guī)劃法求最長公共子序列以及最長公共子字符串相關(guān)實現(xiàn)技巧,需要的朋友可以參考下
    2018-08-08
  • 最新評論