装载Bean
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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">
<!--扫描包组件-->
<!--使用全路径扫描-->
<context:component-scan base-package="com.service"></context:component-scan>
<context:component-scan base-package="com.dao"></context:component-scan>
<context:component-scan base-package="com.entity"></context:component-scan>
<!--使用通配符扫描-->
<!--如果不写会扫描当前目录下面的所有后代包
如果带*通配符,它只能扫描子包
-->
<!-- <context:component-scan base-package="com.*"></context:component-scan>-->
<bean id="qr" class="org.apache.commons.dbutils.QueryRunner" ></bean>
</beans>
类的注解:
- Component 不分类型万能注解 可以在括号中增加字符串 是bean在容器中的id
- Service 一般用于业务层 效果用法同上
- Repository 一般用于持久层 效果用法同上
- Controller 一般用于控制层 效果用法同上
Bean的依赖注入
- 普通类型的set注入:在需要注入的属性加@Value注解
- 复杂类型的set注入
a.根据类型注入 @Autowired(必须) 配合@Qualifier(“id”)支持ID匹配
b.JSR-250 @Resource 不带参数是类型匹配 带参数配合name属性支持ID匹配
c.JSR-330 @Inject 类型匹配 @Name(“id”) 支持ID匹配
继承JUnit
引用junit包和spring-text组件
需要注解:
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations = “classpath:applicationContext.xml”) [locations的值支持数组,单个可以直接写字符串]
Bean其他注解
生命周期:
- 初始化方法 方法上加@PostConstruct
- 销毁方法 方法上加@PreDestroy
作用域:
在bean的顶部加上 @Scope("") 注解的内容可以的是singleton或者prototype…
示例
@Repository("userDao")
public class UserDaoImpl implements IUserDao{
@Resource(name="qr")
private QueryRunner qr ;
@Override
public UserBean findByNameAndPassword(String name, String password) {
String sql = "select * from user where name=? and password=? ";
UserBean user = null;
try {
user = qr.query(DruidUtil.getConn(),sql,new BeanHandler<>(UserBean.class),name,password);
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}
@Service("userService")
public class UserServiceImpl implements IUserService{
@Resource(name = "userDao")
private IUserDao dao;
@Override
public boolean login(String name, String password) {
UserBean user = dao.findByNameAndPassword(name,password);
if(user!=null){
return true;
}
UserBean user1 = new UserBean();
return false;
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestSpring {
@Resource(name="userService")
private IUserService service;
@Test
public void test1(){
boolean l =service.login("xiaowang","123456");
System.out.println(l);
}
}