Java Novice Learning Guide [day35]---Spring Quick Start

1. Spring overview

Spring is an open source lightweight inversion of control (IOC) and aspect-oriented programming (AOP) container framework (high cohesion, low coupling) -> Spring integrates almost all frameworks on the market

Note: Spring underlying principle: xml+dom4j+factory design pattern+reflection

IOC/DI control rollover/dependency injection

  • Give your class to Spring for management, and Spring will be responsible for the creation and maintenance of objects, [initialization, destruction] simple interest mode, multi-case mode

  • Get objects from Spring

Insert picture description here

2. Getting started with spring

1. Dynamic web engineering

2. Guide the package, guide whichever package you need, don’t import it all at once

3. Spring configuration file

  • View through Baidu or official documents
  • Introduce constraints, convenient and prompt
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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">
	<bean id="..." class="...">
	<!-- collaborators and configuration for this bean go here -->
	</bean>
</beans>

4. Ways to obtain objects (two)

  • BeanFactory creation object [3.2.4] obsolete

  • @Test
    	public void testBeanFactory() throws Exception {
          
          
    		//第一步:读取资源文件
    		Resource resource = new ClassPathResource("applicationContext.xml");
    		//第二步:拿到核心对象 BeanFactory
    		BeanFactory factory = new XmlBeanFactory(resource);
        }
    
  • ApplicationContext (pay attention to the pilot package)

@Test
	public void testApplicationContext() throws Exception {
    
    //这个要先导包
		//加载工程classpath下的配置文件实例化
		String conf = "applicationContext.xml";
		ApplicationContext factory = new ClassPathXmlApplicationContext(conf);
    }

The difference between the above two types of acquisition objects

The difference and connection between BeanFactory and ApplicationContext

  • ApplicationContext interface extends BeanFactory interface child has extension to the parent, functionally speaking, the parent is more powerful

  • BeanFactory: lazy loading mode, create objects only when needed

  • ApplicationContext: Load urgently, regardless of whether you need it or not, you will get the object when you come up

3. Dependency injection

1. XML injection (must have a corresponding setter method)

2. Annotation injection (@Autowired provides annotations for Spring, which need to be imported)

Insert picture description here

4. Spring and details

1. Spring test

Need advanced guide package

*spring-test-4.1.2**.RELEASE.jar* *–* *Test package*

*spring-aop-4.1.2.RELEASE.jar* *–* *AOP包***

/**
 * @author wlk
 *可以通过注解来启动spring
 */
@RunWith(SpringJUnit4ClassRunner.class)//是在配置文件中设置value值
@ContextConfiguration("classpath:applicationContext.xml")//一般就使用这个
//@ContextConfiguration("/cn/xxxx/springtest/SpringTest-context.xml")
//@ContextConfiguration
/*还有多种写法
 * 2、写在当前包下时@ContextConfiguration("\cn\xxxx\springtest\SpringTest-context.xml")  包路劲
 * 3、@ContextConfiguration     默认在当前包中   测试类名-context.xml
 * */
public class SpringTest {
    
    
	//自动注入,会从spring中找对应的bean
	@Autowired
	Date date;
	@Autowired
	HelloBean hbBean;
	@Test
	public void testSpring() throws Exception {
    
    
		System.out.println(date);
		System.out.println(hbBean);
	}

}

2. Configuration details

/**
 * @author wlk
 *细节配置  init-method指定初始化方法,destroy-method指定销毁方法 
 *lazy-init指定懒加载模式,懒模式就是需要对象的时候才会去加载
 *scope设置单例或者多例模式(默认为单例)
 *singleton单例/prototype多例
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class DetailBeanTest {
    
    
	@Autowired
	ApplicationContext context;

	@Test
	public void testDetail() {
    
    
		System.out.println(context);
		 DetailBean bean1 = context.getBean("detail",DetailBean.class);
		// DetailBean bean2 = context.getBean("detail",DetailBean.class);
		 System.out.println(bean1);
		// System.out.println(bean2);
	}
}

5. Use spring in a three-tier architecture

1. dao+service

  • Dao writes Dao and puts it in applicationContext.xml and gives it to Spring to manage and use SpringTest to test

  • Service write the service

    • Put it into applicationConxtext.xml and give it to Spring to manage and use SpringTest to test
    • Inject Dao
<!-- 4、三层结构在spring中的使用 -->
	<bean id="daoimpl" class="cn.xxxx.dao.impl.UserDaoImpl"></bean>
	<bean id="serviceimpl" class="cn.xxxx.service.impl.UserServiceImpl">
		<property name="dao" ref="daoimpl"></property>
	</bean>

2、controller

The goal is: to start spring at the same time as tomcat starts to obtain the objects of the service layer

1. You want to get the object from the service layer.
2. When tomcat is loaded, spring also injects it, so you need to add a listener.
3. Get the Spring container to get the service object inside.

Configure monitoring in web.xml

<!-- 加入spring的监听 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>

In the Servlet initialization method, get the Service object and assign it to the Servlet field

//执行Servlet之前,执行初始化方法,去Spring中,获取到UserServiceImpl的对象,并赋值给usi;
	@Override
	public void init() throws ServletException {
    
    
		//上下文对象
		ServletContext sc = this.getServletContext();
		//Spring容器对象
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc);
			usi = context.getBean("service", UserServiceImpl.class);
	}

Guess you like

Origin blog.csdn.net/WLK0423/article/details/110875032
Recommended