我想知道我是否正确地注释了这些类,因为我是注释的新手:
国家.java
@Component
public class Country {
private int countryId;
private String countryName;
private String countryCode;
/**
* No args constructor
*/
public Country() {
}
/**
* @param countryId
* @param countryName
* @param countryCode
*/
public Country(int countryId, String countryName, String countryCode) {
this.countryId = countryId;
this.countryName = countryName;
this.countryCode = countryCode;
}
//getters and setters
}
CountryDAO.java
@Repository
public interface CountryDAO {
public List<Country> getCountryList();
public void saveCountry(Country country);
public void updateCountry(Country country);
}
JdbcCountryDAO.java
@Component
public class JdbcCountryDAO extends JdbcDaoSupport implements CountryDAO{
private final Logger logger = Logger.getLogger(getClass());
@Autowired
public List<Country> getCountryList() {
int countryId = 6;
String countryCode = "AI";
logger.debug("In getCountryList()");
String sql = "SELECT * FROM TBLCOUNTRY WHERE countryId = ? AND countryCode = ?";
logger.debug("Executing getCountryList String "+sql);
Object[] parameters = new Object[] {countryId, countryCode};
logger.info(sql);
//List<Country> countryList = getJdbcTemplate().query(sql,new CountryMapper());
List<Country> countryList = getJdbcTemplate().query(sql, parameters,new CountryMapper());
return countryList;
}
CountryManagerIFace.java
@Repository
public interface CountryManagerIFace extends Serializable{
public void saveCountry(Country country);
public List<Country> getCountries();
}
CountryManager.java
@Component
public class CountryManager implements CountryManagerIFace{
@Autowired
private CountryDAO countryDao;
public void saveCountry(Country country) {
countryDao.saveCountry(country);
}
public List<Country> getCountries() {
return countryDao.getCountryList();
}
public void setCountryDao(CountryDAO countryDao){
this.countryDao = countryDao;
}
}
请您参考如下方法:
这个答案应该会把事情搞清楚一点:What's the difference between @Component, @Repository & @Service annotations in Spring?
其他你应该知道的事情:
您的实体和接口(interface)不需要任何注解。实际上,@Component 和其他派生注释只是意味着您正在动态声明一个 Spring bean。例如,
@Component public class MyComponent { ... }
默认情况下会在 Spring 的上下文中添加一个名为“myComponent”的 bean。 Spring bean 默认是单例的,代表真实的实例化对象。
因此,将实体或接口(interface)声明为 Spring bean 是没有意义的。管理器在语义上与服务相同,因此您应该使用@Service 对它们进行注释。
你的代码应该是这样的:
// No annotation
public class Country {
和
// No annotation
public interface CountryDAO {
和
@Repository
public class JdbcCountryDAO extends JdbcDaoSupport implements CountryDAO {
和
// No annotation
public interface CountryManagerIFace extends Serializable{
和
@Service
public class CountryManager implements CountryManagerIFace{
@Autowired
private CountryDAO countryDao;
注意:我很少在我的代码中使用@Component,因为@Controller(表示层)、@Service(服务层)和@Repository(dao 层)涵盖了我主要的 Spring bean 需求。