使用注解配置Bean
1、在需要定义Bean的类上添加注解:@Component("bookDao")
@Component
业务层的Bean:@Service
数据层的Bean:@Repository
表现层的Bean:@Controller
四种注解功能一样,只是方便理解
@Component("bookDao")
public class BookDaoImpl implements BookDao{
}
若括号中不指定名称,则getBean时应使用类型获取。
public class App {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
System.out.println(bookDao);
BookService bookService = ctx.getBean(BookService.class);
System.out.println(bookService);
}
}
2、在xml文件中,开启context命名空间
3、用context开启组件扫描
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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">
<!-- 1、开启context命名空间-->
<!-- 使用context空间加载properties文件-->
<context:property-placeholder location="jdbc.properties" system-properties-mode="NEVER"/>
<!-- 开启组件扫描-->
<context:component-scan base-package="com.hyk"/>
</beans>
结果