Spring入门


Spring

Spring是一个轻量级控制反转(IoC)和面向切面(AOP)的容器框架。

DI 依赖注入

◆目的:解决企业应用开发的复杂性

◆功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能

◆范围:任何Java应用

普通对象的创建:

方式一:

User user=new User();

方式二反射(可以达到解耦):

Object object = Class.forName("com.testfan.ioc.User").newInstance();

Spring对象的创建:

第一种方式:

通过xml维护bean对象

调用

//spring ioc
//spring.xml是bean的配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
User user2= (User) context.getBean("user");

xml的创建方法:

image-20200412115023212

配置填写:

<?xml version="1.0" encoding="UTF-8"?>


	

第二种方式:

注解加包扫描

@Component //注解
public class Car {
	
	private Car() {
		System.out.println("create Car ");
	}

}

xml配置中添加包扫描

	  
    

注意会爆红:

补全xml的表头

<?xml version="1.0" encoding="UTF-8"?>

调用

Car car = (Car) context.getBean("car"); //by name
User user =(User) context.getBean(Car.class);//by type
System.out.println(car);

注意:

@Component 如果默认没有添加名字的话使用默认的类名小写context.getBean("car")
@Component(cartest)  默认的时候要用context.getBean("cartest")

单例模式:

spring的单例模式:

xml:

//scope="singleton"单例模式  scope="prototype"非单例模式,每次创建一个新的对象
 

注解:

@Scope("prototype") 默认不添加注解就是非单例模式添加的时候就是单例模式
手写单例模式

口诀:构造方法私有化

//手写单例
public class Singleton {
	private static Singleton singleton;
	
	
	public static synchronized Singleton getSingleton() {
		if(singleton==null) {
			singleton =new Singleton();
		}
		return singleton;
	}
	

	private Singleton() {
		System.out.println("create Singleton ");
	}
	
	public static void main(String[] args) {
		Singleton singleton =new Singleton();
		Singleton singleton2 =new Singleton();
	}
}
 

DI:

依赖注入

第一种方法xml:

注意需要写set方法,不然会报错

	
	 //配置需要注入的类名car ,ref是获取时候的名称
	

调用:

ApplicationContext context = new ClassPathXmlApplicationContext("spring1.xml");
User user =(User) context.getBean("user");
System.out.println(user.getCar());
第二种注解:
	@Autowired//注意需要写get方法,不需要set方法 by name
	@Autowired(required=flase) //如果添加了required,不检查这个类是不是存在 
	private User user;

	@Resource(name="user") by type
	private User user;

	public User getUser() {
		return user;
	}

调用:

Car car = (Car) context.getBean("car");
System.out.println("user1"+car.getUser());

输出结果:
user1User [name=null, sex=null, age=0]

javabean中值的定义:

第一种:

普通值的定义

image-20200412165516195

xml中添加:


 //赋值给name

list类型值添加
		
			
			
			
			
		
set类型值添加
		
			
			
			
			
		

第二种读取properties

properties
name=\u5f20\u4e09\u0089
num=101

xml中添加如下,用来解析properties

	

user对象

注解方式获取
@Component("cartest")
public class Car {
	@Value("${name}")
	private String name;
	@Value("${num}")
	private double price;

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	
	@Override
	public String toString() {
		return "Car [name=" + name + ", price=" + price + "]";
	}
}
xml中的获取

		
		//通过$获取到properties中的name值
	

m(业务)v(试图jsp)c(控制)

junit集成

	
		junit
		junit
		4.12
		test
	
	  
        org.springframework  
        spring-test  
        ${org.springframework-version}
        provided  
    

添加对应的注解

@RunWith(SpringJUnit4ClassRunner.class)//junit整合spring的
测试//立马开启了spring的注解
@ContextConfiguration(locations= {"classpath:spring1.xml"})//
加载核心配置文件
public class JunitTest {
	
	@Autowired
	User user;
	
	@Test
	public void test() {
		System.err.println(user);
		assertTrue("成功",true);
	}
	
}

testng的集成

mvn依赖

		  
            org.springframework  
            spring-test  
            ${org.springframework-version}
            provided  
         
              
            org.testng
            testng
			${testng.version}
            test
        

代码实列:

@ContextConfiguration(locations = { "classpath:spring1.xml" })//添加对应的注解
public class NewTest {
//	@Autowired
//	Car car;
	
	@Test
	public void f() {
		ApplicationContext context = new ClassPathXmlApplicationContext("spring1.xml");
		Car car = (Car) context.getBean("cartest");
		System.out.println("user"+car.getUser());
	}

}

spring_jdbctemplate(数据库)

mvn依赖包

org.springframework
spring-jdbc
 当前系统版本 
provided

	
			
			com.mchange
			c3p0
			0.9.5.4
		
		
			mysql
			mysql-connector-java
			8.0.18
		
当前版本一般是指spring的版本号:
${org.springframework-version}
jdbc.properties配置文件配置
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc\:mysql\://118.24.13.38\:3308/goods?characterEncoding=utf-8&useSSL=false
jdbc.username=zhangsan
jdbc.password=123123
jdbc.initPoolSize=5
jdbc.maxPoolSize=10
spring-db.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>

	
	
	
	
	
			
			
			
			
			
			
	
	
	
	
		
	
	



代码:

TestUserd对象

package com.testfan.jdbc;


/**
 * @author pc
 *
 */
public class TestUser {
	private String uid;
	private String loginname;
	private String loginpass;
	public String getUid() {
		return uid;
	}
	public void setUid(String uid) {
		this.uid = uid;
	}
	public String getLoginname() {
		return loginname;
	}
	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}
	public String getLoginpass() {
		return loginpass;
	}
	public void setLoginpass(String loginpass) {
		this.loginpass = loginpass;
	}
	@Override
	public String toString() {
		return "TestUser [uid=" + uid + ", loginname=" + loginname + ", loginpass=" + loginpass + "]";
	}
}

jdbc代码实现
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)	
@ContextConfiguration(locations = {"classpath:spring-db.xml"})
public class SpringJdbcTest {
	
	@Autowired
	JdbcTemplate jdbcTemplate;
	
	@Test
	public void testUpdate() {
		String sql = "UPDATE t_user_test SET loginname = ? WHERE uid = ?";
		jdbcTemplate.update(sql, "test1","1");
	}
	
	@Test
	public void testQueryOne() {
		String sql = "select * from t_user_test where uid =?";
		RowMapper rowMapper = new BeanPropertyRowMapper<>(TestUser.class);
		TestUser user = jdbcTemplate.queryForObject(sql, rowMapper,"1");
		System.out.println(user);
	}
	
	@Test
	public void testQueryForList() {
		String sql = "select * from t_user_test";
		RowMapper rowMapper = new BeanPropertyRowMapper<>(TestUser.class);
		List user = jdbcTemplate.query(sql, rowMapper);
		System.out.println(user.size());
	}
	
	@Test
	public  void testQueryMap() {
		String sql = "select * from t_user_test";
		List> user = jdbcTemplate.queryForList(sql);
		System.out.println(user);
	}
	
	

}