Spring 常用註解

@Controller 控制器註解
@RequestMapping 設置訪問URL註解

@AutoWired 自動注入Bean註解,一般在需要配置固定參數時使用。


web.xml配置:

<servlet>
  	<servlet-name>dispatcherServlet</servlet-name>         
  	<servlet-class>              
  		org.springframework.web.servlet.DispatcherServlet         
  	</servlet-class>          
	<init-param>              
	  	<param-name>contextConfigLocation</param-name>              
	  	<param-value>/WEB-INF/config/spring/spring-datasource.xml</param-value>         
  	</init-param>          
  	<load-on-startup>1</load-on-startup>     
  </servlet>     
  	
  <servlet-mapping>          
  	<servlet-name>dispatcherServlet</servlet-name>         
	<url-pattern>*.do</url-pattern>     
  </servlet-mapping>




spring-datasource.xml  掃描註解

<!-- 使Spring關注ANNOTATION -->
<context:annotation-config />


@Controller 和@RequestMapping 使用方式

@Controller
@RequestMapping("/TestServlet")
public class TestServlet {
	
	@RequestMapping(method = RequestMethod.POST)
	public String doPost(HttpServletRequest request,HttpServletResponse response){
		return "TestServlet 內部的 doPost方法";
	}
}

訪問地址爲:http://ip:端口號/項目名稱/TestServlet , 請求方式爲 post 就能夠訪問上面示例中的doPost()方法。


@AutoWired 自動注入Bean註解,一般在需要配置固定參數時使用。正常情況下不建議使用。

public class StudentBean {
	private String name;
	private String sex;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
}

@Controller@RequestMapping("/TestServlet")
public class TestServlet {
	@Autowired
	private StudentBean student;
	@RequestMapping(method = RequestMethod.POST)
	public String doPost(HttpServletRequest request,HttpServletResponse response){
		return "TestServlet 內部的 doPost方法";	
	}
}

spring-datasource.xml配置:

<!-- 引用@Autowired必須定義這個bean --> 
    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
    
    <!-- 通過構造方法裝配的Bean --> 
    <bean id="student" class="com.XXX.test.StudentBean"> 
    	<property name="name" value="小明"/>
    	<property name="sex" value="男"/>
    	<!-- <constructor-arg index="0" type="java.lang.String" value="aaaa"/>  -->
    </bean> 
    <!-- @Autowired注入位置 --> 
    <bean id="testServlet" class="com.XXX.test.TestServlet"/> 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章