Spring learning notes, spring learning notes
XML configuration
<?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>
Call the xml file code
ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");PersonService personService=(PersonService)ctx.getBean("personService");personService.save();
Personservicebean Method
package cn.cast.service.impl;import javax.annotation.Resource;import org.springframework.stereotype.Service;import cn.cast.service.PersonService;import cn.cast.dao.PersonDao;@Servicepublic class PersonServiceBean implements PersonService {@Resourceprivate PersonDao personDaoBean;public void show() {personDaoBean.show();}public void setPersonDaoBean(PersonDao personDaoBean) {this.personDaoBean = personDaoBean;}public PersonDao getPersonDaoBean() {return personDaoBean;}}
Persondaobean Method
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 ("execute the add () method in the PersonDaoBean ");}}
Test Method
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();}}
-- Define Bean annotations
@ Controller
@ Controller ("Bean name ")
Define control layer beans, such as Action
@ Service
@ Service ("Bean name ")
Define service layer Bean
@ Repository
@ Repository ("Bean name ")
Define DAO layer Bean
@ Component
Bean definition, which is not suitable for classification.
-- Define Bean scope and lifecycle
@ Scope ("prototype ")
Values: singleton, prototype, session, request, session, globalSession
@ PostConstruct
It is equivalent to init-method. It is used in the method and executed during Bean initialization.
@ PreDestroy
This is equivalent to destory-method. It is used in the method and executed when the Bean is destroyed.