文章目录
Spring2.5引入使用注解定义Bean
@Component 描述Spring框架中的Bean
@Repository用于对DAO实现类进行标注
@Service用于对Service实现类进行标注
@Controller用于对Controller实现类进行标注
找文档:
spring-framework-4.2.4.RELEASE/docs/spring-framework-reference/html/xsd-configuration.html
找到下面的,40.2.8the context schema
<?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 http://www.springframework.org/schema/context/spring-context.xsd"> <!-- bean definitions here -->
<!--开启注解扫描-->
<context:component-scan base-packge="xx包名"/>
</beans>
新建UserService类
/**
* Spring的Bean管理的注解方式:
* * 传统方式需要去XML中配置<bean id="" class=""></bean>
*/
@Component("userService")
public class UserService {
public String sayHello(String name){
return "Hello" + name;
}
}
新建测试类
@Test
public void demo1(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) applicationContext.getBean("userService");
String s = userService.sayHello("张三");
System.out.println(s);
}