目的
让spring统一管理对象的创建
引用
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
xml方式
配置
resources/bean.xml
<!--默认单例-->
<bean id="user" class="com.alvin.pojo.User" scope="singleton"/>
<!--初始化-->
<bean id="user2" class="com.alvin.pojo.User" init-method="init" destroy-method="destroy"/>
<!--静态工厂方式创建实例-->
<bean id="user3" class="com.alvin.utils.BeanFactory" factory-method="createUser"/>
<!--实例工厂模式创建对象-->
<bean id="objectFactory" class="com.alvin.utils.ObjectFactory"/>
<bean id="user4" class="com.alvin.pojo.User" factory-bean="objectFactory" factory-method="createUser"/>
<!--依赖注入!!!-->
<bean id="date" class="java.util.Date"/>
<!--构造方法注入-->
<bean id="user5" class="com.alvin.pojo.User">
<constructor-arg name="id" value="1"/>
<constructor-arg name="name" value="alvin"/>
<constructor-arg name="birthDay" ref="date"/>
</bean>
<!--set注入-->
<bean id="user6" class="com.alvin.pojo.User">
<property name="id" value="2"/>
<property name="name" value="alvin"/>
<property name="birthDay" ref="date"/>
</bean>
<!--p注入,本质还是set-->
<bean id="user7" class="com.alvin.pojo.User" p:id="3" p:name="alvin" p:birthDay-ref="date"/>
<!--集合注入-->
<bean id="user8" class="com.alvin.pojo.User">
<property name="objectArrays">
<array>
<value>123</value>
<bean class="java.util.Date"/>
<ref bean="date"/>
</array>
</property>
<property name="objectList">
<list>
<value>123</value>
<bean class="java.util.Date"/>
<ref bean="date"/>
</list>
</property>
<property name="objectSet">
<set>
<value>123</value>
<bean class="java.util.Date"/>
<ref bean="date"/>
</set>
</property>
<property name="objectMap">
<map>
<entry key="alvin" value="123"/>
<entry key-ref="date" value="123"/>
<entry key="123" value-ref="date"/>
</map>
</property>
<property name="properties">
<props>
<prop key="alvin">123</prop>
</props>
</property>
</bean>
配置实例
<!--c3p0 datasource-->
<bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/db_test?characterEncoding=utf-8"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
<!--queryRunner-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="ds"/>
</bean>
<bean id="favoriteMapper" class="com.alvin.mapper.impl.FavoriteMapperImpl">
<property name="queryRunner" ref="queryRunner"/>
</bean>
<bean id="favoriteService" class="com.alvin.service.impl.FavoriteServiceImpl">
<property name="favoriteMapper" ref="favoriteMapper"/>
</bean>
使用
ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("bean.xml");
User user = (User) context.getBean("user");
底层简单模拟
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class BeanFactory {
//用来加载properties配置文件的类
private static Properties props = new Properties();
//是一个容器,用来存放bean,相当于Spring IOC的核心容器
private static Map<String, Object> beans = new HashMap<String, Object>();
//使用静态代码块加载配置文件,以及实例化bean
static {
//使用类加载器获取配置文件
InputStream inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.properties");
//使用properties类加载配置文件
try {
props.load(inputStream);
//解析properties类
//获取所有的key
Set<Object> set = props.keySet();
//遍历获取到的key
for (Object key : set) {
//根据key,获取配置文件中的值
//获取到的值,就是需要实例化的全限定名例如com.alvin.driver.impl.MySQLDriver
String value = (String) props.get(key);
//使用反射的方式实例化这个bean
Object object = Class.forName(value).newInstance();
//把实例和实例对应的名字,放到容器中
beans.put(key.toString(),object);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object getBean(String name) {
return beans.get(name);
}
}
全注解方式
基础
# 创建对象
@Component
@Controller
@Service
@Repository
# 注入数据
@Autowired 按照bean的class注入
@Qualifier 按照bean的id注入
@Resource 不推荐
@Value 注入基本数据类型和 String
# 改变作用范围
@Scope bean的作用范围,取值:singleton prototype request session globalsession
# 生命周期相关
@PostConstruct 初始化方法
@PreDestroy 销毁方法
# 其他
@Configuration spring 配置类
@ComponentScan 扫描的包
@Bean 写在方法上,表明使用此方法创建一个对象
@PropertySource 加载.properties 文件中的配置
@Import 导入其他配置类
包扫描方式
配置
<context:component-scan base-package="com.alvin"/>
使用
context = new ClassPathXmlApplicationContext("annoBeans.xml");
config方式
配置
jdbcConfig.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_test?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
config/Spring.config
@Configuration
@ComponentScan("com.alvin")
@Import(JdbcConfig.class)
public class SpringConfig {
}
config/Jdbc.config
@Configuration
@PropertySource("classpath:jdbcConfig.properties")
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public ComboPooledDataSource createDataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
} catch (Exception e) {
e.printStackTrace();
}
return dataSource;
}
@Bean
public QueryRunner createQueryRunner() {
return new QueryRunner(createDataSource());
}
}
在impl.class中注解
@Repository
public class FavoriteMapperImpl implements FavoriteMapper {
@Autowired
private QueryRunner queryRunner;
public void setQueryRunner(QueryRunner queryRunner) {
this.queryRunner = queryRunner;
}
public List<Favorite> queryAll() throws Exception {
String sql = "select * from tab_favorite";
List<Favorite> favoriteList = queryRunner.query(sql, new BeanListHandler<Favorite>(Favorite.class));
return favoriteList;
}
}
使用
context = new AnnotationConfigApplicationContext(SpringConfig.class);
FavoriteService favoriteService = context.getBean(FavoriteService.class);
spring整合junit
引用
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
<scope>test</scope>
</dependency>
示例
import javax.annotation.Resource;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
//@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class springTest extends AbstractJUnit4SpringContextTests {
@Resource
private FavoriteService favoriteService;
@Test
public void method1() throws Exception {
List<Favorite> favorites = favoriteService.queryAll();
System.out.println(favorites);
}
}