Guice——轻量级注解Guice简单之美

Guice是谷歌推出的一个轻量级依赖注入框架,帮助我们解决Java项目中的依赖注入问题。如果只想在项目中使用依赖注入,这时候我们可以考虑使用Guice,不需要使用Spring那个庞然大物。本文参考了Guice官方文档,详细信息可以直接查看Guice文档

一、引入依赖

maven配置

<dependency>
    <groupId>com.google.inject</groupId>
    <artifactId>guice</artifactId>
    <version>4.1.0</version>
</dependency>

gradle配置

compile group: 'com.google.inject', name: 'guice', version: '4.1.0'

二、Guice+mybatis项目搭建

下面将以Guice结合mybatis搭建一个简单的项目,更好的去了解。

maven项目目录

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.leejlife</groupId>
	<artifactId>guice</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<name>guice</name>
	<url></url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<guice.version>3.0</guice.version>
		<mybatis.version>3.2.6</mybatis.version>
		<mybatis-guice.version>3.6</mybatis-guice.version>
		<mysql-jdbc.version>5.1.38</mysql-jdbc.version>
		<mchange.c3p0.version>0.9.2.1</mchange.c3p0.version>
		<c3p0.version>0.9.2.1</c3p0.version>
		<slf4j.version>1.7.5</slf4j.version>
		<logback.version>1.0.13</logback.version>
	</properties>

<!-- https://mvnrepository.com/artifact/org.jboss.netty/netty -->
	<dependencies>
		<dependency>
			<groupId>mysql</groupId>		
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.38</version>
		</dependency>
		<dependency>
	        <groupId>commons-configuration</groupId>
	        <artifactId>commons-configuration</artifactId>
	        <version>1.5</version>
	    </dependency>
	    <dependency>
			<groupId>com.google.inject</groupId>
			<artifactId>guice</artifactId>
			<version>${guice.version}</version>
		</dependency>
		<dependency>
			<groupId>com.google.guiceberry</groupId>
			<artifactId>guiceberry</artifactId>
			<version>3.3.1</version>
			<scope>test</scope>
		</dependency>
	    <dependency>
			<groupId>com.google.inject.extensions</groupId>
			<artifactId>guice-persist</artifactId>
			<version>${guice.version}</version>
		</dependency>
		<dependency>
			<groupId>com.google.inject.extensions</groupId>
			<artifactId>guice-multibindings</artifactId>
			<version>${guice.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-guice</artifactId>
			<version>${mybatis-guice.version}</version>
		</dependency>
		<dependency>
			<groupId>com.mchange</groupId>
			<artifactId>c3p0</artifactId>
			<version>${mchange.c3p0.version}</version>
		</dependency>
		<dependency>
	  		<groupId>org.apache.commons</groupId>
	    	<artifactId>commons-lang3</artifactId>
	    	<version>3.5</version>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<version>${logback.version}</version>
		</dependency>

		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-core</artifactId>
			<version>${logback.version}</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		
	</dependencies>
	<build>
		<filters>
			<filter>../guice/profile-${profiles.active}.properties</filter>
		</filters>

		<resources>
			<resource>
				<filtering>true</filtering>
				<directory>src/main/resources</directory>
				<includes>
					<include>**/*.properties</include>
					<include>**/*.xml</include>
				</includes>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-deploy-plugin</artifactId>
				<version>2.4</version>
				<configuration>
					<skip>true</skip>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>1.5</version>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
						<configuration>
							<shadedArtifactAttached>true</shadedArtifactAttached>
							<shadedClassifierName>allinone</shadedClassifierName>
							<artifactSet>
								<includes>
									<include>*:*</include>
								</includes>
							</artifactSet>
							<transformers>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>reference.conf</resource>
								</transformer>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
									<manifestEntries>
										<Main-Class>com.leejlife.guice.GuiceServer</Main-Class>
									</manifestEntries>
								</transformer>
							</transformers>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
	<profiles>
		<profile>
			<id>dev</id>
			<properties>
				<profiles.active>dev</profiles.active>
			</properties>
			<activation>
				<activeByDefault>true</activeByDefault>
			</activation>
		</profile>
		<profile>
			<id>sit</id>
			<properties>
				<profiles.active>sit</profiles.active>
			</properties>
		</profile>
		<profile>
			<id>prod</id>
			<properties>
				<profiles.active>prod</profiles.active>
			</properties>
		</profile>
	</profiles>
</project>

DBMapper.java

package com.leejlife.guice.model;
public interface DBMapper {
	String selectMaxData();
}

DBMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.leejlife.guice.model.DBMapper">
	<select id="selectMaxData" resultType="String">
		select max(data) from t_test
	</select>
</mapper>

DBModule.java

package com.leejlife.guice.module;

import java.util.Properties;

import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.mybatis.guice.MyBatisModule;
import org.mybatis.guice.datasource.c3p0.C3p0DataSourceProvider;

import com.google.inject.PrivateModule;
import com.google.inject.name.Names;
import com.leejlife.guice.model.DBMapper;

public class DBModule extends PrivateModule {
	@Override
	protected void configure() {
		this.install(new MyBatisModule() {
			@Override
			protected void initialize() {
				bindDataSourceProviderType(C3p0DataSourceProvider.class);
				bindTransactionFactoryType(JdbcTransactionFactory.class);
				addMapperClass(DBMapper.class);
				Names.bindProperties(binder(),
						createProperties("db.properties"));
			}
		});
		expose(DBMapper.class);
	}

	private Properties createProperties(String configFile) {
		Properties result = new Properties();
		try {
			result.load(DBModule.class.getClassLoader()
					.getResourceAsStream(configFile));
			return result;
		} catch (Exception e) {
			throw new RuntimeException("can not load " + configFile + " .", e);
		}
	}
}

Module.java

package com.leejlife.guice.module;


import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import com.leejlife.guice.service.ProcessService;

public class Module extends AbstractModule {

	@Override
	protected void configure() {
		install(new DBModule());
		bind(ProcessService.class).in(Scopes.SINGLETON);
	}
}

ProcessService.java使用注解

package com.leejlife.guice.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.leejlife.guice.model.DBMapper;

public class ProcessService {
	private final static Logger log = LoggerFactory.getLogger(ProcessService.class);

	@Inject
	private DBMapper dbMapper;
		
	public void process(){
		log.info("mabatis查询出最大Data:"+dbMapper.selectMaxData());
	}
}

MainServer.java

package com.leejlife.guice;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.leejlife.guice.module.Module;
import com.leejlife.guice.service.ProcessService;

/**
 * Hello world!
 *
 */
public class MainServer {
	public static void main(String[] args) {
		Injector injector = Guice.createInjector(new Module());
		ProcessService processService = injector
				.getInstance(ProcessService.class);

		processService.process();

		System.exit(0);
	}
}

配置文件

db.properties
mybatis.environment.id = guice
JDBC.driver=${JDBC.driver}
JDBC.url=${JDBC.url}
JDBC.username=${JDBC.username}
JDBC.password=${JDBC.password}

c3p0.maxPoolSize=40
c3p0.minPoolSize=10
c3p0.acquireIncrement=2
c3p0.maxIdleTime=1800
c3p0.idleConnectionTestPeriod=60
c3p0.testConnectionOnCheckout = false
c3p0.testConnectionOnCheckin = true
#client will wait 30s to get a connection
c3p0.checkoutTimeout=30000 

配置profile-dev.properties,注意配上自己的数据源。这里使用的是mysql

#mysql connection

JDBC.driver=com.mysql.jdbc.Driver
JDBC.url=
JDBC.username=
JDBC.password=


#c3p0 config
c3p0.maxPoolSize=40
c3p0.minPoolSize=10
c3p0.acquireIncrement=2
c3p0.maxIdleTime=1800
c3p0.idleConnectionTestPeriod=60
c3p0.testConnectionOnCheckout = false
c3p0.testConnectionOnCheckin = true
#client will wait 30s to get a connection
c3p0.checkoutTimeout=30000

执行main方法。成功

 

 

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值