总起:
spring的ioc注入有三种方式:
(1)构造方法:例如
<bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
(2)setter方式:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
</bean>
(3)注解方式:
标记spring需要加载进bean容器的关键字:
按使用场景分
(1)@Repository 用于持久层
(2)@Service(“accountService”)用于业务层
(3)@Controller 用于表现层
(4)@Component(“accountService”) 其他
注入使用bean容器中类实例关键字:
(1)@Resource(name=“accountDao”) java自带
(2)spring中定义的
@Autowired
@Qualifier(“accountDao”)
private AccountDao accountDao;
1、注解方式配置bean,类似xml改成java类配置,实例如下
package config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import javax.sql.DataSource;
@Configuration
@ComponentScan(basePackages = {"com.fang"})
@Import({JdbcConfig.class})
public class SpringConfiguration {
@Bean
@Scope("prototype")
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
@Bean(name="dataSource")
public DataSource CreateDataSource(){
try{
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/test");
ds.setUser("root");
ds.setPassword("123456");
return ds;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}