裝載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);
}
}