文章目录
spring中的注解是用来代替xml中繁琐的配置而生的。本文从原始注解和新注解两方面来说明注解的使用。
1 原始注解
applicationContext.xml中指定需要扫描的包或类,spring来识别使用注解配置的类、字段和方法。
<beans xmlns="http://www.springframework.org/schema/beans"
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">
<!--扫描com.test包下所有的类-->
<context:component-scan base-package="com.test"/>
</beans>
1.1 实例化对象的注解
<bean>用来定义将类对象的创建交由spring容器来完成,相应的注解有如下几个(根据实际情况选择一个使用):
注解 | 说明 |
---|---|
@Component | 可在所有类上使用 |
@Controller | 在controller类上使用,同时起到标注的作用 |
@Service | 在service类上使用,同时起到标注的作用 |
@Repository | 在dao类上使用,同时起到标注的作用 |
测试@Repository
@Repository("testDao")
public class TestDaoImp implements TestDao {
public void queryAll() {
System.err.println("queryAll执行了");
}
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
TestDao testDao = (TestDao) applicationContext.getBean("testDao");
testDao.queryAll();
}
}
<