1. 程式人生 > >JAVA框架 Spring 註解註入

JAVA框架 Spring 註解註入

.html class IT soft pri 涵蓋 java 復制 掃描

一、首先需要引入jar包:spring-aop-4.2.4.RELEASE.jar。(在spring解壓包libs內)。

二、如果註解方式註入依賴的對象,需要引用新的約束。

技術分享圖片

內的:xsd-configuration.html。打開網頁中的:the context schema 粘貼復制:

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
" 4 xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" 5 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 6 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
"> <!-- bean definitions here --> 7 8 </beans>

技術分享圖片

寫接口和實現類:

1 package jd.com.inject;
2 
3 public interface Indemo {
4     void  save();
5 }

實現類:需要寫註解:@Component(value = "indemo") 其中value是配置文件中的id值,在調用的時候執行方法getbean(id值)調用就是這個值。

 1 package jd.com.inject;
 2 
 3 
 4 import org.springframework.stereotype.Component;
5 6 @Component(value = "indemo") 7 public class indemoIpl implements Indemo { 8 @Override 9 public void save() { 10 System.out.println("調用業務層。"); 11 } 12 }

配置文件(applicationContenxt.xml)

需要開啟掃描組件:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
 5         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 6         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->
 7 
 8 
 9         <context:component-scan base-package="jd.com" />
10 
11 </beans>

其中:

<context:component-scan base-package="jd.com" /> 其中base-package是需要掃描的包。需要註意:這裏寫的是jd.com而不是完整的包。這樣涵蓋所有包。

測試類:
 1 package jd.com.inject;
 2 
 3 import org.junit.Test;
 4 import org.springframework.context.ApplicationContext;
 5 import org.springframework.context.support.ClassPathXmlApplicationContext;
 6 
 7 public class TestDemo {
 8     @Test
 9     public  void   testdemo(){
10         ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
11         indemoIpl in= (indemoIpl) ac.getBean("indemo");
12         in.save();
13     }
14 
15 
16 }

這樣就是實現註解方式註入。


JAVA框架 Spring 註解註入