导入依赖
<!--spring依赖 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.9.RELEASE</version> </dependency> <!--日志包--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.25</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>首先在applicationContext.xml开启包扫描
<?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"> <context:component-scan base-package="com.lyf"></context:component-scan> </beans>创建person类
public class Person { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }创建Persondao,并添加@Repository
@Repository public class PersonDao { public Person find(Person p) { if ("jack".equals(p.getUsername())&&"12345".equals(p.getPassword())){ return p; } else { return null; } } }创建personservice并添加@Service,相当于在xml中配置了一个bean标签 zaiservice使用@Autowired注入dao层对象
//相当于在xml中配置了一个bean标签 @Service public class PersonService { private static final Logger log= LoggerFactory.getLogger(PersonService.class); @Autowired PersonDao personDao ; public boolean login(Person p) { log.debug(p+" login"); Person person = personDao.find(p); if(person==null) { return false; }else{ return true; } } }测试
public class Test01SpringIoc { private static final Logger log= LoggerFactory.getLogger(Test01SpringIoc.class); private ClassPathXmlApplicationContext context; @Before public void init(){ //创建ioc 容器对象,暂时看成map context = new ClassPathXmlApplicationContext("applicationContext.xml"); } @Test public void test09(){ //PersonService personService = new PersonService(); PersonService personService = (PersonService) context.getBean("personService"); Person p = new Person(); p.setUsername("jack"); p.setPassword("12345"); boolean flag =personService.login(p); log.debug(flag+""); } }