Spring通过注解装配Bean
通过注解实现ServiceImpl业务
一、使用@Component装配Bean
1、 定义类:User
在类上面加@Component注解,在属性上面加@Value值
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.wbg.springxmlbean.entity; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component(value = "user") public class User { @Value("2") private int id; @Value("韦邦杠") private String name; @Value("18") private int age; private Role role; @Override public String toString() { return "User{" + "id=" + id + ", role=" + role + ", name='" + name + '\'' + ", age=" + age + '}'; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } }
2、使用@ComponentScan注解进行扫描包的路径
创建一个类,类上面加@CompontScan注解
测试:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
ApplicationContext context=new AnnotationConfigApplicationContext(PojoConfig.class); User user=context.getBean(User.class); System.out.println(user);
3、创建UserService接口
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public interface UserService { User getUser(); void setUser(User user); }
4、创建实现类UserServiceImpl,在该类上面使用@Component注解
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.wbg.springxmlbean.service.impl; import com.wbg.springxmlbean.entity.User; import com.wbg.springxmlbean.service.UserService; import org.springframework.stereotype.Component; /** * 这里的@Component 表名它是一个Spring所需要的 Bean * 而且也实现了对于的UserService接口所定义的方法getUser、setUser */ @Component public class UserServiceImpl implements UserService { private User user; @Override public User getUser() { return user; } @Override public void setUser(User user){ System.out.println("进入了UserServiceImpl.setUser"); System.out.println(user); } }
5、配置@ComponentScan制定包扫描
创建一个ApplicationConfig类,该类上面使用@ComponentScan注解
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.wbg.springxmlbean.service.impl; import com.wbg.springxmlbean.entity.User; import org.springframework.context.annotation.ComponentScan; /** * basePackageClasses直接扫描指定类 */ @ComponentScan(basePackageClasses = {User.class,UserServiceImpl.class}) /** * basePackages可读性好,但不建议使用,因为修改包名没有提示 */ //@ComponentScan(basePackages = {"com.wbg.springxmlbean.entity","com.wbg.springxmlbean.service"}) public class ApplicationConfig { }
测试:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
ApplicationContext context=new AnnotationConfigApplicationContext(ApplicationConfig.class); User user=context.getBean(User.class); UserService userService=context.getBean(UserService.class); userService.setUser(user)
二、自动装配-@Autowired
eneity的Role类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.wbg.springxmlbean.entity; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class Role { @Value("1") private int id; @Value("roleName_1") private String roleName; @Value("note_1") private String note; @Override public String toString() { return "Role{" + "id=" + id + ", roleName='" + roleName + '\'' + ", note='" + note + '\'' + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
service创建接口:RoleService
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.wbg.springxmlbean.service; public interface RoleService { void printRoleInfo(); }
impl实现类:RoleServiceImpl
@Component public class RoleServiceImpl implements RoleService { @Autowired private Role role; @Override public void printRoleInfo() { System.out.println(role); } }
创建xml扫描:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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-4.3.xsd"> <!--指定要扫描的包,如果有多个可以用逗号隔开--> <context:component-scan base-package="com.wbg.springxmlbean.service,com.wbg.springxmlbean.entity"/> </beans>
测试:
ApplicationContext context=new ClassPathXmlApplicationContext("Role12.xml"); RoleService userService=context.getBean(RoleService.class); userService.printRoleInfo();
当有注解的时候
当没有的时候
三、注解@Primary
上面类:RoleServiceImpl实现了RoleService接口
再创建一个类RoleServiceImpl2进行实现RoleService接口
则RoleService接口就有两个实现类,但Spring ioc不知道采用哪个注入,然后就会出错
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@Component public class RoleServiceImpl2 implements RoleService { @Autowired private Role role; @Override public void printRoleInfo() { System.out.println("进入了RoleServiceImpl22"); System.out.println(role); } }
在启动的时候报错
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.wbg.springxmlbean.service.RoleService' available: expected single matching bean but found 2: roleServiceImpl,roleServiceImpl2
通过@Primary注解告诉Sring ioc
测试:
1、RoleServiceImpl2
去掉RoleServiceImpl2上面的@primary注解
测试RoleServiceImpl
四、注解@Qualifier
把上面的@Primary注解去掉,然后在Controller进行使用
现在接口AdminService有两个实现类
AdminServiceImpl
AdminServiceImpl2
然后在Controller进行实现
五、使用@Bean装配Bean
@Bean的配置项中包含4个配置
name:是一个字符中数组,允许多个
autowire:标识是否是一个引用Bean对象,默认值:Autowire.NO
initMethd:自定义初始化方法
destroyMethod:自定义销毁方法
代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.wbg.springxmlbean.spring; import com.mchange.v2.c3p0.ComboPooledDataSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; import java.beans.PropertyVetoException; @Configuration public class ConfigDataSource { @Bean(name = "dataSource") public DataSource getDataSource() throws PropertyVetoException { ComboPooledDataSource dataSource=new ComboPooledDataSource(); dataSource.setDriverClass("org.mariadb.jdbc.Driver"); dataSource.setJdbcUrl("jdbc:mariadb://localhost:3306/wbg_logistics"); dataSource.setUser("root"); dataSource.setPassword("123456"); dataSource.setMaxPoolSize(30); return dataSource; } }
实现:
接口:
public interface RoleDataSourceService { Role getRole(int id); }
实现接口
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.wbg.springxmlbean.service.impl; import com.wbg.springxmlbean.entity.Role; import com.wbg.springxmlbean.service.RoleDataSourceService; import com.wbg.springxmlbean.spring.ConfigDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.beans.PropertyVetoException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @Component public class RoleDataSourceServiceImpl implements RoleDataSourceService { @Autowired ConfigDataSource dataSource=null; @Override public Role getRole(int id) { Connection con=null; ResultSet rs=null; PreparedStatement ps=null; Role role=null; try { con=dataSource.getDataSource().getConnection(); ps=con.prepareStatement("select * from role where id = ?"); ps.setInt(1,id); rs=ps.executeQuery(); while (rs.next()){ role=new Role(); role.setId(rs.getInt(1)); role.setNote(rs.getString(2)); role.setNote(rs.getString(3)); } } catch (PropertyVetoException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return role; } }
这里Role12.xml需要扫描:
测试:
ApplicationContext context=new ClassPathXmlApplicationContext("Role12.xml"); RoleDataSourceService roleDataSourceService=context.getBean(RoleDataSourceService.class); System.out.println(roleDataSourceService.getRole(1));
六、装配的混合使用
创建一个配置类:
@ComponentScan(basePackages = "com.wbg.springxmlbean.service") @ImportResource({"classpath:spring-dataSource.xml"}) public class ApplicationConfig { }
创建xml文件:
spring-dataSource.xml
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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 "> <!--创建数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="org.mariadb.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mariadb://localhost:3306/wbg_logistics" /> <property name="user" value="root" /> <property name="password" value="123456" /> <property name="maxPoolSize" value="30" /> <property name="minPoolSize" value="10" /> <property name="autoCommitOnClose" value="false" /> <property name="checkoutTimeout" value="10000" /> <property name="acquireRetryAttempts" value="2" /> </bean> </beans>
创建接口:RoleDataSourceService2
创建实现类:
使用注解@Autowired
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.wbg.springxmlbean.service; import com.wbg.springxmlbean.entity.Role; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.sql.DataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @Service public class RoleDataSourceService2Impl implements RoleDataSourceService2 { @Autowired DataSource dataSource; @Override public Role getRole(int id) { Connection con=null; ResultSet rs=null; PreparedStatement ps=null; Role role=null; try { con= dataSource.getConnection(); ps=con.prepareStatement("select * from role where id = ?"); ps.setInt(1,id); rs=ps.executeQuery(); while (rs.next()){ role=new Role(); role.setId(rs.getInt(1)); role.setRoleName(rs.getString(2)); role.setNote(rs.getString(3)); } } catch (SQLException e) { e.printStackTrace(); } return role; } }
测试:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
ApplicationContext context=new AnnotationConfigApplicationContext(ApplicationConfig.class); RoleDataSourceService2 roleDataSourceService=context.getBean(RoleDataSourceService2.class); System.out.println(roleDataSourceService.getRole(2));