为什么使用注解开发?
从前面的内容我们可以发现,Spring
开发中有许多的配置,非常的费时费力,影响开发效率。 Spring
本身就是一个轻代码而重配置的框架,配置比较繁重,影响开发效率,所以就在Spring
中加入了注解,使用注解代替原来的xml
配置文件,这样就可以简化配置,提升开发效率。
Spring开发中的常用注解
Bean管理类常用的四个注解(作用相同,名称不同)
注解 用法 @Component 使用在类上用于实例化Bean @Controller 使用在表现层类 上用于实例化Bean(作用于@Component一致) @Service 使用在业务层类 上用于实例化Bean(作用于@Component一致) @Repository 使用在持久层类 上用于实例化Bean(作用于@Component一致)
依赖注入相关的注解(加在成员变量上)
注解 用法 @Value 简单类型(基本类型+字符串) @Autowired 默认按类型进行自动装配(自定义引用类型),不看引用类的注解名称 @Qualifier 不能单独使用,必须和@Autowired
一起使用。强制使用名称注入(选择名称为value
值的对象注入) @Resource Java提供的注解,也可以达到强制使用名称注入的作用(此注解单独使用,使用name
参数指定名称)
对象生命周期注解
注解 用法 @Scope 取值singleton
(单例),prototype
(多例)
初始化方法和销毁方法
注解 用法 @PostConstruct 相当于init-method
该注解作用在方法上 @PreDestroy 相当于destroy-method
该注解作用在方法上
其他注解
注解 用法 @Configuration 声明当前类是一个配置类 @ComponentScan 扫描指定的包路径 @Import 用于导入其他配置类 @PropertySource 用于加载.properties
文件中的配置 @Bean 只能写到方法上,表明使用此方法创建一个对象,并把创建好的对象保存到IOC容器中 @RunWith 用Spring
整合JUnit
,可以实现简化测试的开发 @ContextConfiguration 用于指定Spring
配置文件 @Test 测试方法
代码示例
1. 导入Maven依赖
< dependencies>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-context</ artifactId>
< version> 5.0.2.RELEASE</ version>
</ dependency>
< dependency>
< groupId> commons-logging</ groupId>
< artifactId> commons-logging</ artifactId>
< version> 1.2</ version>
</ dependency>
< dependency>
< groupId> log4j</ groupId>
< artifactId> log4j</ artifactId>
< version> 1.2.12</ version>
</ dependency>
< dependency>
< groupId> junit</ groupId>
< artifactId> junit</ artifactId>
< version> 4.12</ version>
< scope> test</ scope>
</ dependency>
< dependency>
< groupId> com.alibaba</ groupId>
< artifactId> druid</ artifactId>
< version> 1.1.10</ version>
</ dependency>
< dependency>
< groupId> mysql</ groupId>
< artifactId> mysql-connector-java</ artifactId>
< version> 5.1.6</ version>
</ dependency>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-test</ artifactId>
< version> 5.0.2.RELEASE</ version>
< scope> test</ scope>
</ dependency>
</ dependencies>
2. 创建实体类(用于接收从数据库中查询到的信息)
package com. qcby. entity ;
public class Account {
private int id;
private String name;
private Double money;
public int getId ( ) {
return id;
}
public void setId ( int id) {
this . id = id;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public double getMoney ( ) {
return money;
}
public void setMoney ( Double money) {
this . money = money;
}
@Override
public String toString ( ) {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}' ;
}
}
3. 编写Service层和Dao层查询
3.1 Service层
package com. qcby. service ;
import com. qcby. entity. Account ;
import java. util. List ;
public interface AccountService {
public List < Account > findAll ( ) ;
}
package com. qcby. service. impl ;
import com. qcby. dao. AccountDao ;
import com. qcby. entity. Account ;
import com. qcby. service. AccountService ;
import org. springframework. beans. factory. annotation. Autowired ;
import org. springframework. stereotype. Service ;
import java. util. List ;
@Service ( "as" )
public class AccountServImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public List < Account > findAll ( ) {
return accountDao. findAll ( ) ;
}
}
3.2 Dao层
package com. qcby. dao ;
import com. qcby. entity. Account ;
import java. util. List ;
public interface AccountDao {
public List < Account > findAll ( ) ;
}
package com. qcby. dao. impl ;
import com. alibaba. druid. pool. DruidDataSource ;
import com. alibaba. druid. pool. DruidPooledConnection ;
import com. qcby. dao. AccountDao ;
import com. qcby. entity. Account ;
import org. springframework. beans. factory. annotation. Autowired ;
import org. springframework. stereotype. Repository ;
import java. sql. PreparedStatement ;
import java. sql. ResultSet ;
import java. sql. SQLException ;
import java. util. ArrayList ;
import java. util. List ;
@Repository ( "ad" )
public class AccountDaoImpl implements AccountDao {
@Autowired
private DruidDataSource druidDataSource;
public List < Account > findAll ( ) {
DruidPooledConnection connection = null ;
PreparedStatement statement = null ;
ResultSet resultSet = null ;
List < Account > list = new ArrayList < Account > ( ) ;
try {
connection = druidDataSource. getConnection ( ) ;
String sql = "select * from account;" ;
statement = connection. prepareStatement ( sql) ;
resultSet = statement. executeQuery ( ) ;
while ( resultSet. next ( ) ) {
Account account = new Account ( ) ;
account. setId ( resultSet. getInt ( "id" ) ) ;
account. setName ( resultSet. getString ( "name" ) ) ;
account. setMoney ( resultSet. getDouble ( "money" ) ) ;
list. add ( account) ;
}
} catch ( SQLException e) {
e. printStackTrace ( ) ;
} finally {
try {
connection. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
try {
statement. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
try {
resultSet. close ( ) ;
} catch ( SQLException e) {
e. printStackTrace ( ) ;
}
}
return list;
}
}
4. 创建配置类(代替xml配置文件)
package com. qcby. uitl ;
import com. alibaba. druid. pool. DruidDataSource ;
import org. springframework. context. annotation. Bean ;
import org. springframework. context. annotation. ComponentScan ;
import org. springframework. context. annotation. Configuration ;
import org. springframework. context. annotation. Import ;
@Configuration
@ComponentScan ( "com.qcby" )
public class SpringConfig {
@Bean ( )
public DruidDataSource createDataSource ( ) {
DruidDataSource druidDataSource = new DruidDataSource ( ) ;
druidDataSource. setDriverClassName ( "com.mysql.jdbc.Driver" ) ;
druidDataSource. setUrl ( "localhost" ) ;
druidDataSource. setUsername ( "admin" ) ;
druidDataSource. setPassword ( "666" ) ;
return druidDataSource;
}
}
5. 在配置文件中开启注解扫描
<?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 = " com.qcby.service" />
< context: component-scan base-package = " com.qcby.entity" />
</ beans>
6. 创建测试类进行测试
import com. qcby. dao. AccountDao ;
import com. qcby. entity. Account ;
import com. qcby. service. AccountService ;
import com. qcby. uitl. SpringConfig ;
import org. junit. Test ;
import org. junit. runner. RunWith ;
import org. springframework. beans. factory. annotation. Autowired ;
import org. springframework. context. ApplicationContext ;
import org. springframework. context. annotation. AnnotationConfigApplicationContext ;
import org. springframework. context. support. ClassPathXmlApplicationContext ;
import org. springframework. test. context. ContextConfiguration ;
import org. springframework. test. context. junit4. SpringJUnit4ClassRunner ;
import java. util. List ;
@RunWith ( SpringJUnit4ClassRunner . class )
@ContextConfiguration ( classes = SpringConfig . class )
public class AccountServiceTest {
@Autowired
private AccountService as;
@Test
public void run ( ) {
List < Account > all = as. findAll ( ) ;
for ( Account a : all) {
System . out. println ( a) ;
}
}
}