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="org.example"/>
</beans>
调用xml文件代码
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
PersonService personService=(PersonService)ctx.getBean("personService");
personService.save();
personservicebean方法
package cn.cast.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.cast.service.PersonService;
import cn.cast.dao.PersonDao;
@Service
public class PersonServiceBean implements PersonService {
@Resource
private PersonDao personDaoBean;
public void show() {
personDaoBean.show();
}
public void setPersonDaoBean(PersonDao personDaoBean) {
this.personDaoBean = personDaoBean;
}
public PersonDao getPersonDaoBean() {
return personDaoBean;
}
}
persondaobean方法
package cn.cast.dao.impl;
import org.springframework.stereotype.Repository;
import cn.cast.dao.PersonDao;
@Repository
public class PersonDaoBean implements PersonDao
{
public void show()
{
System.out.println("执行PersonDaoBean中的add()方法");
}
}
测试方法
package cn.cast.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.cast.service.PersonService;
public class Testmain {
public static void main(String args[]){
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
PersonService personService=(PersonService)ctx.getBean("personServiceBean");
personService.show();
}
}
--定义Bean的注解
@Controller
@Controller("Bean的名称")
定义控制层Bean,如Action
@Service
@Service("Bean的名称")
定义业务层Bean
@Repository
@Repository("Bean的名称")
定义DAO层Bean
@Component
定义Bean, 不好归类时使用.
--定义Bean的作用域和生命过程
@Scope("prototype")
值有:singleton,prototype,session,request,session,globalSession
@PostConstruct
相当于init-method,使用在方法上,当Bean初始化时执行。
@PreDestroy
相当于destory-method,使用在方法上,当Bean销毁时执行。