Struts 2和hibernate也使用注解,但是使用注解在以后的开发中应用不多。但是可以说在整合的时候如何进行注解开发。在Spring中,注解必须会玩。
package cn.itcast.spring3.demo1; import org.springframework.stereotype.Component; /** * 注解的方式装配Bean. * @author zhongzh * */ //在Spring配置文件中<bean id="userService" class="cn.itcast.demo1.UserService"> //其实也需要核心配置文件,只不过不是用来装配bean了,你得告诉Spring需要去哪些包下面去扫描.它得扫描到这些注解才行.它得去哪里扫描你得告诉人家才行 //@Component(value="userService") @Component("userService") public class UserService { public void sayHello(){ System.out.println("Hello Spring Annotation....."); } }
<?xml version="1.0" encoding="UTF-8"?> <!-- 基于注解的开发需要引入context命名空间。它就是用来配置去扫描哪些包的. --> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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"> <context:annotation-config></context:annotation-config><!-- XML和注解混搭的时候用的 --> <!-- 告诉Spring你要扫描哪些包下的东西 --> <!-- <context:component-scan base-package="cn.itcast.spring3.demo1"> --> <context:component-scan base-package="cn.itcast.spring3.demo1"><!-- 纯注解用扫描的就行 --> </context:component-scan> </beans>
package cn.itcast.spring3.demo1; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; //注解的方式:都是将类装载到容器中. public class SpringTest1 { @Test public void demo1(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = (UserService) applicationContext.getBean("userService"); userService.sayHello(); } }