注解
1. 注解方式IoC只是标记哪些类要被Spring管理
@Component
public class Xxx {
}
//@Repository(value = "dao")
@Repository("dao")
//当注解中只设置一个属性时,value属性的属性名可以省略
public class XxxDao {
//默认情况:
// 类名首字母小写就是 bean 的 id。例如:XxxController 类对应的 bean 的 id 就是 xxxController
//也可
@Service
public class XxxService {
}
@Controller
public class XxxController {
}
2. 我们还需要XML方式或者Java配置类方式指定注解生效的
<?xml version="1.0" encoding="UTF-8"?>
<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 https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 1.注解方式IoC只是标记哪些类要被Spring管理
我们还需要XML方式或者Java配置类方式指定注解生效的
-->
<context:component-scan base-package="com.wind.annotation"/>
</beans>
最后进行测试
public class AnnotationTest {
@Test
public void test1() {
//建立容器对象
ClassPathXmlApplicationContext classPathXmlApplicationContext =
new ClassPathXmlApplicationContext("spring-annotation.xml");
// 利用注解 获取组件
XxxController bean = classPathXmlApplicationContext.getBean(XxxController.class);
System.out.println("+++++++@Controller+++++++");
System.out.println(bean);
Object xxxDao = classPathXmlApplicationContext.getBean("dao");
System.out.println("+++++++@Repository+++++++");
System.out.println(xxxDao);
XxxService xxxService = classPathXmlApplicationContext.getBean("xxxService", XxxService.class);
System.out.println("+++++++@Service+++++++");
System.out.println(xxxService);
}
}