Spring Bean定義的三種方式


<!--Spring容器啟動配置(web.xml文件)-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

 

一、基於XML的配置

適用場景:

  • Bean實現類來自第三方類庫,如:DataSource等
  • 需要命名空間配置,如:context,aop,mvc等
<beans>
<import resource=“resource1.xml” />//導入其他配置文件Bean的定義
<import resource=“resource2.xml” />

<bean id="userService" class="cn.lovepi.***.UserService" init-method="init" destory-method="destory"> </bean> <bean id="message" class="java.lang.String">   <constructor-arg index="0" value="test"></constructor-arg> </bean> </beans>

 

二、基於注解的配置

適用場景:

  • 項目中自己開發使用的類,如controller、service、dao等

步驟如下:

1. 在applicationContext.xml配置掃描包路徑

<context:component-scan base-package="com.lovepi.spring"> 
  <context:include-filter type="regex" expression="com.lovepi.spring.*"/>   //包含的目標類
  <context:exclude-filter type="aspectj" expression="cn.lovepi..*Controller+"/>   //排除的目標類
</context:component-scan>

 注:<context:component-scan/> 其實已經包含了 <context:annotation-config/>的功能

 

2. 使用注解聲明bean

Spring提供了四個注解,這些注解的作用與上面的XML定義bean效果一致,在於將組件交給Spring容器管理。組件的名稱默認是類名(首字母變小寫),可以自己修改:

  • @Component:當對組件的層次難以定位的時候使用這個注解
  • @Controller:表示控制層的組件
  • @Service:表示業務邏輯層的組件
  • @Repository:表示數據訪問層的組件
@Service
public class SysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    public int insertSelective(SysUser record){
        return sysUserMapper.insertSelective(record);
    }

}

三、基於Java類的配置

適用場景:

  • 需要通過代碼控制對象創建邏輯的場景
  • 實現零配置,消除xml配置文件

步驟如下:

  1. 使用@Configuration注解需要作為配置的類,表示該類將定義Bean的元數據
  2. 使用@Bean注解相應的方法,該方法名默認就是Bean的名稱,該方法返回值就是Bean的對象。
  3. AnnotationConfigApplicationContext或子類進行加載基於java類的配置
@Configuration  
public class BeansConfiguration {  

    @Bean  
    public Student student(){  
        Student student=new Student();  
        student.setName("張三");  
        student.setTeacher(teacher());  
        return student;  
    }  

    @Bean  
    public Teacher teacher(){  
        Teacher teacher=new Teacher();  
        teacher.setName("李四");  
        return teacher;  
    }  

}  

 

public class Main {  

    public static void main(String args[]){  
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeansConfiguration.class);  
        Student student = (Student) context.getBean("student");
        Teacher teacher = (Teacher) context.getBean("teacher");
        System.out.println("學生的姓名:" + student.getName() + "。老師是" + student.getTeacher().getName());  
        System.out.println("老師的姓名:" + teacher.getName());  
    }  

} 

 

 參考:https://blog.csdn.net/lzh657083979/article/details/78524489

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM