使用注解开发需要在配置文件中进行配置注解;
<!-- 开启注解开发 --> <context:annotation-config/> <!-- 在类中写了注解。还需要进行包的扫描找到 -->
<context:component-scan base-package="dao"></context:component-scan>
base-package:是扫描需要注解的包的全包名路径
注解开发
一、创建Bean的注解
1、@Componet 在当前的bean不知道在那一层的时候使用
2、@Repository 用于dao层。
3、@Service 用于service层。
4、@Controller 用于表现层。
二、注入注解
1、@Value("") 简单注入:
可以在变量属性中注入,也可以在setter方法中注入。 (写在属性中,可以不创建get、set方法)
2、@ Autowired 复杂注入:自动装配。 (默认是根据类型来装配的。)
3、@ Qualifier("") 预防多个bean自动装配分别不了
4、@Resource(name = "")
三、其他注解
1、@Scope(" ") 其实这个属性和想xml中的bean的Scope属性的配置。可以设置为 单列、多列等。
2、@PostConstruct 初始化;
3、@PreDestroy 销毁方法;
Junit开发
需要导入spring-text的jar包。可以进行Junit测试
@RunWith(SpringJUnit4ClassRunner.class) //使用RunWith 然后找到配置文件 @ContextConfiguration(locations = "classpath:spring/application.xml") public class text { @Autowired //使用动态装配进行 ways way; //需要装配的类 @Test //需要 public void texting() { way.text(); //需要测试的方法。 } }
spring在web中的应用
需要导入spring-web的jar包
1、配置监听器
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
这个ContextLoaderListener实现了servletContextListener接口,在这个监听器中,当服务器启动时,
会找applicationContext对象,其实它是一个实现类webApplicationContext对象存入servletContext中。
2、在web.xml中配置applicationContext.xml配置文件
默认情况下,会在WEB-INF目录下找applicationContext文件。如果该路径下没有这个文件,
则,就需要进行配置。
//classpath: 配置文件的路径。
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/application.xml</param-value>
</context-param>